import {
  Box,
  Button,
  IconButton,
  Typography,
  Select as MuiSelect,
  MenuItem,
  useTheme,
  useMediaQuery,
  Skeleton,
  FormControl,
  Select,
} from "@mui/material";
import moment from "moment";
import HeaderFull from "@ui_kit/Header/HeaderFull";
import SectionWrapper from "@ui_kit/SectionWrapper";
import { FC, useEffect, useState } from "react";
import { FileExportIcon } from "./icons/FileExporIcon";
import { UpdateIcon } from "./icons/UpdateIcon";
// import { Select } from "../../pages/Questions/Select";
import { CheckboxSelect } from "../../ui_kit/CheckboxSelect";
import { CardAnswer } from "./CardAnswer";
import { FilterIcon } from "./icons/FilterIcon";
import { FilterModal } from "@ui_kit/Modal/FilterModal/FilterModal";
import { ExportContactsModal } from "@ui_kit/Modal/ExportContactsModal";

import { resultApi } from "@api/result";
import { useObsolescenceIdResult, useResultStore } from "@root/results/store";
import { answerResultListExport, setResults } from "@root/results/actions";

import { quizApi } from "@api/quiz";
import { setQuizes } from "@root/quizes/actions";
import { useCurrentQuiz, useQuizes } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import { questionApi } from "@api/question";
import { setQuestions } from "@root/questions/actions";
import ArrowDown from "@icons/ArrowDownIcon";

const options = [
  { label: "Муром (1)", value: "option1" },
  { label: "Москва (1)", value: "option2" },
];

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

// let lossDebouncer: null | ReturnType<typeof setTimeout> = null;
// let lossId: string[] = [] as string[];
//
// const onLossNew = (id: string) => {
//   //Если в массиве ещё нет такого id - добавляем
//   if (!lossId.includes(id)) lossId.push(id);
//   //Если таймер есть - сбрасываем
//   if (typeof lossDebouncer === "number") clearTimeout(lossDebouncer);
//   //Назначем новый таймер
//   lossDebouncer = setTimeout(async () => {
//     //стреляем на лишение новизны
//     await obsolescenceResult(lossId);
//     //сбрасываем массив
//     lossId = [];
//   }, 3000);
// };

const resetTime = (date: number) => {
  console.log(date);
  let a = Math.round(date / 86400) * 86400 - 97200;
  console.log(a);
  console.log(moment.unix(a).format("dddd, MMMM Do YYYY, h:mm:ss "));
  return moment.unix(a).format("dddd, MMMM Do YYYY, h:mm:ss ");
};

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 [exportContactsModalOpen, setExportContactsModalOpen] =
    useState<boolean>(false);
  const [filterNew, setFilterNew] = useState<string>("Все заявки");
  const [filterDate, setFilterDate] = useState<string>("За все время");

  const quizList = useQuizStore();
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { results } = useResultStore();
  const { total_count } = useResultStore();
  // const {idResultArray, addIdResult, clearIdResultArray} = useObsolescenceIdResult()
  useEffect(() => {
    const getData = async () => {
      if (editQuizId !== null) {
        const quizes = await quizApi.getList();
        setQuizes(quizes);

        const questions = await questionApi.getList({ quiz_id: editQuizId });
        setQuestions(questions);

        const result = await resultApi.getList(editQuizId);
        setResults(result);
      }
    };
    getData();
  }, []);

  const DateDefinition = (result: string) => {
    //определяем когда был получен результат - вчера, сегодня или число и месяц
    let restime = new Date(result);
    let timeCompleting = Date.parse(String(result));
    const timeNow = Date.now();
    let dayResult;
    if (timeNow - timeCompleting < 86400000) {
      dayResult = "Сегодня";
    }
    if (172800000 > timeNow - timeCompleting > 86400000) {
      dayResult = "Вчера";
    } else {
      dayResult = restime.toLocaleDateString();
    }
    return dayResult;
  };
  const TimeDefinition = (result: string) => {
    //достаём время
    let timeResult = new Date(result).toLocaleTimeString().slice(0, -3);
    return timeResult;
  };

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

  return (
    <Box>
      <HeaderFull isRequest={true} />
      <SectionWrapper
        sx={{ padding: isMobile ? "0 16px" : "20px" }}
        maxWidth="lg"
      >
        <Typography
          sx={{ fontSize: "36px", fontWeight: "500", mb: "50px", mt: "60px" }}
        >
          {quiz.name}
        </Typography>

        <Box
          sx={{
            width: "100%",
            display: isTablet ? "flex" : "-moz-initial",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Box sx={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <Typography sx={{ fontSize: "18px", color: "#4D4D4D" }}>
              Ответы на квиз
            </Typography>
            <Typography sx={{ fontSize: "18px", color: "#9A9AAF" }}>
              ({total_count})
            </Typography>
          </Box>

          <Box
            sx={{
              mt: "20px",
              mb: "31px",
              gap: "30px",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              width: isTablet ? "auto" : "100%",
            }}
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
              <IconButton
                onClick={() => {
                  // answerResultListExport(editQuizId)
                  setExportContactsModalOpen(true);
                }}
                sx={{
                  width: "44px",
                  height: "44px",
                  borderRadius: "8px",
                  border: "1px solid #7E2AEA",
                }}
              >
                <FileExportIcon />
              </IconButton>
              <IconButton
                sx={{
                  width: "44px",
                  height: "44px",
                  borderRadius: "8px",
                  border: "1px solid #7E2AEA",
                }}
                onClick={async () => {
                  const result = await resultApi.getList(editQuizId);
                  console.log(result);
                  setResults(result);
                }}
              >
                <UpdateIcon />
              </IconButton>

              {isTablet && (
                <IconButton
                  onClick={() => setFilterModalOpen(true)}
                  sx={{
                    background: "#fff",
                    width: "44px",
                    height: "44px",
                    borderRadius: "8px",
                    border: "1px solid #7E2AEA",
                  }}
                >
                  <FilterIcon />
                </IconButton>
              )}
            </Box>

            {!isTablet && (
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  gap: "20px",
                  width: "100%",
                  justifyContent: "flex-end",
                }}
              >
                <FormControl
                  fullWidth
                  sx={{ maxWidth: "223px", width: "100%" }}
                >
                  <Select
                    id="display-select"
                    variant="outlined"
                    value={filterDate}
                    onChange={(event) => {
                      setFilterDate(event.target.value as string);
                    }}
                    sx={{
                      width: "100%",
                      height: "48px",
                      borderRadius: "8px",
                      "& .MuiOutlinedInput-notchedOutline": {
                        border: `1px solid #7E2AEA !important`,
                        borderRadius: "10px",
                      },
                    }}
                    MenuProps={{
                      PaperProps: {
                        sx: {
                          mt: "8px",
                          p: "4px",
                          borderRadius: "8px",
                          backgroundColor: theme.palette.background.default,
                          border: "1px solid #EEE4FC",
                          boxShadow: "0px 8px 24px rgba(210, 208, 225, 0.4)",
                        },
                      },
                      MenuListProps: {
                        sx: {
                          py: 0,
                          display: "flex",
                          flexDirection: "column",
                          gap: "8px",
                          "& .Mui-selected": {
                            backgroundColor: theme.palette.background.default,
                            color: "#7E2AEA",
                          },
                        },
                      },
                    }}
                    inputProps={{
                      sx: {
                        color: "#7E2AEA",
                        display: "block",
                        px: "9px",
                        gap: "20px",
                        width: "90%",
                      },
                    }}
                    IconComponent={(props) => <ArrowDown {...props} />}
                  >
                    {itemsTime.map((item, index) => (
                      <MenuItem
                        key={item + index}
                        value={item}
                        sx={{
                          display: "flex",
                          alignItems: "center",
                          gap: "20px",
                          padding: "10px",
                          borderRadius: "5px",
                          color: "#9A9AAF",
                          whiteSpace: "normal",
                        }}
                      >
                        {item}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl
                  fullWidth
                  sx={{ maxWidth: "223px", width: "100%" }}
                >
                  <Select
                    id="display-select"
                    variant="outlined"
                    value={filterNew}
                    onChange={(event) => {
                      setFilterNew(event.target.value as string);
                    }}
                    sx={{
                      width: "100%",
                      height: "48px",
                      borderRadius: "8px",
                      "& .MuiOutlinedInput-notchedOutline": {
                        border: `1px solid #7E2AEA !important`,
                        borderRadius: "10px",
                      },
                    }}
                    MenuProps={{
                      PaperProps: {
                        sx: {
                          mt: "8px",
                          p: "4px",
                          borderRadius: "8px",
                          backgroundColor: theme.palette.background.default,
                          border: "1px solid #EEE4FC",
                          boxShadow: "0px 8px 24px rgba(210, 208, 225, 0.4)",
                        },
                      },
                      MenuListProps: {
                        sx: {
                          py: 0,
                          display: "flex",
                          flexDirection: "column",
                          gap: "8px",
                          "& .Mui-selected": {
                            backgroundColor: theme.palette.background.default,
                            color: "#7E2AEA",
                          },
                        },
                      },
                    }}
                    inputProps={{
                      sx: {
                        color: "#7E2AEA",
                        display: "block",
                        px: "9px",
                        gap: "20px",
                        width: "90%",
                      },
                    }}
                    IconComponent={(props) => <ArrowDown {...props} />}
                  >
                    {["Все заявки", "Новые"].map((item, index) => (
                      <MenuItem
                        key={item + index}
                        value={item}
                        sx={{
                          display: "flex",
                          alignItems: "center",
                          gap: "20px",
                          padding: "10px",
                          borderRadius: "5px",
                          color: "#9A9AAF",
                          whiteSpace: "normal",
                        }}
                      >
                        {item}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                {/* <CheckboxSelect
                  sx={{ maxWidth: "223px", width: "100%" }}
                  placeholder="Выберите город"
                  options={options}
                /> */}

                <Button
                  onClick={() => {
                    setFilterNew("Все заявки");
                    setFilterDate("За все время");
                  }}
                  sx={{
                    maxWidth: "200px",
                    width: "100%",
                    height: "48px",
                    borderRadius: "8px",
                    border: "1px solid #7E2AEA",
                    color: "#7E2AEA",
                  }}
                >
                  Сбросить фильтры
                </Button>
              </Box>
            )}
          </Box>
        </Box>

        {!isTablet && (
          <Box
            sx={{
              display: "flex",
              width: "100%",
              alignItems: "center",
              mb: "15px",
            }}
          >
            <Typography sx={{ fontSize: "18px", color: "#9A9AAF", mr: "40px" }}>
              № заявки
            </Typography>
            <Typography sx={{ fontSize: "18px", color: "#9A9AAF" }}>
              Дата
            </Typography>
            <Typography
              sx={{ fontSize: "18px", color: "#9A9AAF", ml: "288px" }}
            >
              Контакты
            </Typography>
          </Box>
        )}

        <Box
          sx={{
            display: "flex",
            alignItems: "flex-start",
            flexDirection: isTablet ? "-moz-initial" : "column",
            flexWrap: isTablet ? "wrap" : "nowrap",
            gap: "20px",
          }}
        >
          {results.map((result) => {
            const dataResult = new Date(result.created_at);
            let dayResult = DateDefinition(result.created_at);
            let timeResult = TimeDefinition(result.created_at);
            return (
              <CardAnswer
                name={result.content.name}
                email={result.content.email}
                isNew={result.new}
                idResult={result.id}
                dayResult={dayResult}
                timeResult={timeResult}
              />
            );
          })}
        </Box>
      </SectionWrapper>

      <FilterModal
        open={filterModalOpen}
        handleClose={() => setFilterModalOpen(false)}
        filterNew={filterNew}
        filterDate={filterDate}
        setFilterNew={setFilterNew}
        setFilterDate={setFilterDate}
      />
      <ExportContactsModal
        editQuizId={editQuizId}
        open={exportContactsModalOpen}
        handleClose={() => setExportContactsModalOpen(false)}
      />
    </Box>
  );
};
