import { Box, Skeleton, useMediaQuery, useTheme } from "@mui/material";
import HeaderFull from "@ui_kit/Header/HeaderFull";
import SectionWrapper from "@ui_kit/SectionWrapper";
import { ChangeEvent, FC, useEffect, useState } from "react";
import { PrePaymentModal } from "./PrePaymentModal";
import { FilterModal } from "@ui_kit/Modal/FilterModal/FilterModal";

import { resultApi } from "@api/result";
import { useResultStore } from "@root/results/store";
import { setResults } from "@root/results/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import { useUserStore } from "@root/user";

import CustomPagination from "@ui_kit/CustomPagination";
import { parseFilters } from "./helper";
import { QuizSettingsMenu } from "./QuizSettingsMenu";
import { AnswerList } from "./AnswerList";
import { useGetData } from "./useGetData";

const itemsTime = [
  "За всё время",
  "Сегодня",
  "Вчера",
  "Последние 7 дней",
  "Последние 30 дней",
  "Этот месяц",
];
const itemsNews = ["Все заявки", "Новые"];

export const QuizAnswersPage: FC = () => {
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(600));

  const [filterModalOpen, setFilterModalOpen] = useState<boolean>(false);
  const [page, setPage] = useState(1);
  const [filterNew, setFilterNew] = useState<string>("Все заявки");
  const [filterDate, setFilterDate] = useState<string>("За всё время");
  const [prePaymentModalOpen, setPrePaymentModalOpen] =
    useState<boolean>(false);
  const { userAccount } = useUserStore();

  const filterNewHC = (value: string) => {
    setFilterNew(value);
  };
  const filterDateHC = (value: string) => {
    setFilterDate(value);
  };

  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { results, total_count } = useResultStore();
  const countPagination =
    typeof total_count === "number" ? Math.ceil(total_count / 10) : 0;
  useGetData(filterNew, filterDate);

  useEffect(() => {
    return setResults([]);
  }, []);

  useEffect(() => {
    if (!userAccount) {
      return;
    }

    if (
      !Object.keys(userAccount.privileges || {}).length ||
      userAccount.privileges?.[""]?.amount === 0
    ) {
      setPrePaymentModalOpen(true);

      return;
    }

    setPrePaymentModalOpen(false);
  }, [userAccount]);

  const PaginationHC = async (e: ChangeEvent<unknown>, value: number) => {
    setPage(value);
    if (editQuizId !== null) {
      const [result, resultError] = await resultApi.getList(
        editQuizId,
        value - 1,
        parseFilters(filterNew, filterDate),
      );

      if (resultError || !result) {
        console.error("An error occurred while receiving data: ", resultError);

        return;
      }

      setResults(result);
    }
  };

  if (quiz === undefined)
    return (
      <Skeleton sx={{ width: "100vw", height: "100vh", transform: "none" }} />
    );

  return (
    <Box>
      <HeaderFull isRequest={true} sx={{ position: "fixed", zIndex: 9 }} />
      <SectionWrapper
        sx={{ padding: isMobile ? "115px 16px" : "115px 20px 20px" }}
        maxWidth="lg"
      >
        <QuizSettingsMenu
          quiz={quiz}
          total_count={total_count}
          isTablet={isTablet}
          filterNew={filterNew}
          filterDate={filterDate}
          setPrePaymentModalOpen={setPrePaymentModalOpen}
          editQuizId={editQuizId}
          page={page}
          setFilterModalOpen={setFilterModalOpen}
          setFilterNew={setFilterNew}
          setFilterDate={setFilterDate}
          filterNewHC={filterNewHC}
          filterDateHC={filterDateHC}
          itemsTime={itemsTime}
          itemsNews={itemsNews}
        />
        <CustomPagination
          countPagination={countPagination}
          page={page}
          onChange={PaginationHC}
        />
        <AnswerList
          isTablet={isTablet}
          results={results}
          setPrePaymentModalOpen={setPrePaymentModalOpen}
        />
      </SectionWrapper>
      <FilterModal
        open={filterModalOpen}
        handleClose={() => setFilterModalOpen(false)}
        filterNew={filterNew}
        filterDate={filterDate}
        setFilterNew={filterNewHC}
        setFilterDate={filterDateHC}
        itemsTime={itemsTime}
        itemsNews={itemsNews}
      />
      <PrePaymentModal
        open={prePaymentModalOpen}
        setOpen={setPrePaymentModalOpen}
      />
    </Box>
  );
};
