import { useState, useMemo } from "react";
import { Box, Button, Typography, useTheme } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { createQuiz, resetEditConfig } from "@root/quizes/actions";
import ComplexNavText from "../ComplexNavText";
import { SearchTemplate } from "./SearchTemplate";
import { SelectCategory } from "./SelectCategory";
import { TEMPLATES } from "./templates";
import { Template } from "./Template";

import HeaderFull from "@ui_kit/Header/HeaderFull";

import SectionWrapper from "@ui_kit/SectionWrapper";

import type { Category, CategoryType } from "./Template";

export default function QuizGallery() {
  const [searchValue, setSearchValue] = useState<string>("");
  const [categoryType, setCategoryType] = useState<CategoryType | "All">("All");
  const navigate = useNavigate();

  const filteredTemplates = useMemo(
    () =>
      categoryType === "All"
        ? TEMPLATES
        : TEMPLATES.filter((item) => item.categoryType === categoryType),
    [categoryType],
  );
  const foundTemplates = useMemo(
    () =>
      filteredTemplates.reduce((total, category) => {
        const templates = category.templates.filter(({ title }) =>
          title.toLowerCase().includes(searchValue.toLowerCase()),
        );

        if (!templates.length) {
          return total;
        }

        return [...total, { ...category, templates }];
      }, [] as Category[]),
    [searchValue, categoryType],
  );

  return (
    <Box>
      <HeaderFull isRequest />
      <SectionWrapper
        maxWidth="lg"
        sx={{ mt: "25px", mb: "74px", padding: "20px" }}
      >
        <ComplexNavText text1="Галерея квизов" />
        <Typography variant="h4" mt="20px" mb="40px">
          Галерея квизов
        </Typography>
        <Box sx={{ width: "100%" }}>
          <Box sx={{ display: "flex", gap: "2%" }}>
            <SearchTemplate
              searchValue={searchValue}
              setSearchValue={setSearchValue}
            />
            <SelectCategory
              categoryType={categoryType}
              setCategoryType={setCategoryType}
            />
          </Box>
        </Box>
        {foundTemplates.map((template) => (
          <Template key={template.category} template={template} />
        ))}
        <Box
          sx={{ width: "100%", borderBottom: "1px solid #9A9AAF", mt: "50px" }}
        />
        <Typography mt="30px" variant="h4">
          Нет подходящего шаблона?
        </Typography>
        <Button
          variant="contained"
          sx={{ px: "20px", mt: "30px" }}
          onClick={() => {
            resetEditConfig();
            createQuiz(navigate);
          }}
        >
          Создать квиз с нуля
        </Button>
      </SectionWrapper>
    </Box>
  );
}
