import { QuestionType } from "@model/question/question";
import {
  Box,
  Button,
  ClickAwayListener,
  Grow,
  MenuItem,
  MenuList,
  Modal,
  Paper,
  Popper,
  Typography,
  useTheme,
} from "@mui/material";
import { changeQuestionType, updateQuestion } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store";
import { updateSomeWorkBackend } from "@root/uiTools/actions";
import type { RefObject } from "react";
import { useState } from "react";
import { BUTTON_TYPE_QUESTIONS } from "../TypeQuestions";

type ChooseAnswerModalProps = {
  open: boolean;
  onClose: () => void;
  anchorRef: RefObject<HTMLDivElement>;
  questionId: string;
  questionContentId: string | null;
  questionType: QuestionType | null;
};

export const ChooseAnswerModal = ({
  open,
  onClose,
  anchorRef,
  questionId,
  questionContentId,
  questionType,
}: ChooseAnswerModalProps) => {
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [selectedValue, setSelectedValue] = useState<QuestionType>("text");
  const { questions } = useQuestionsStore();
  const theme = useTheme();

  return (
    <>
      <Popper
        placement="right-start"
        open={open}
        anchorEl={anchorRef.current}
        transition
        sx={{ zIndex: 1 }}
      >
        {({ TransitionProps }) => (
          <Grow {...TransitionProps}>
            <Paper>
              <ClickAwayListener onClickAway={onClose}>
                <MenuList autoFocusItem={open}>
                  {BUTTON_TYPE_QUESTIONS.map(({ icon, title, value }) => (
                    <MenuItem
                      key={value}
                      sx={{ display: "flex", gap: "10px" }}
                      {...(value !== questionType && {
                        onClick: () => {
                          onClose();
                          setOpenModal(true);
                          setSelectedValue(value);
                        },
                      })}
                    >
                      <Box>{icon}</Box>
                      <Typography
                        sx={{
                          color:
                            value === questionType
                              ? theme.palette.brightPurple.main
                              : theme.palette.grey2.main,
                        }}
                      >
                        {title}
                      </Typography>
                    </MenuItem>
                  ))}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Grow>
        )}
      </Popper>
      <Modal open={openModal} onClose={() => setOpenModal(false)}>
        <Box
          sx={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            padding: "30px",
            borderRadius: "10px",
            background: "#FFFFFF",
          }}
        >
          <Typography variant="h6" sx={{ textAlign: "center" }}>
            Все настройки, кроме заголовка вопроса будут сброшены <br />
            (вопрос всё ещё будет участвовать в ветвлении, но его условия будут
            сброшены)
          </Typography>
          <Box
            sx={{
              marginTop: "30px",
              display: "flex",
              justifyContent: "center",
              gap: "15px",
            }}
          >
            <Button
              variant="contained"
              sx={{ minWidth: "150px" }}
              onClick={() => setOpenModal(false)}
            >
              Отмена
            </Button>
            <Button
              variant="contained"
              sx={{ minWidth: "150px" }}
              onClick={async () => {
                if (questionContentId === null) return;

                updateSomeWorkBackend(true);
                setOpenModal(false);
                const clearQuestions = [] as string[];

                //записываем потомков , а их результаты удаляем
                const getChildren = (questionContentId: string) => {
                  questions.forEach((targetQuestion) => {
                    if (
                      targetQuestion.type !== null &&
                      targetQuestion.content.rule.parentId === questionContentId
                    ) {
                      //если у вопроса совпал родитель с родителем => он потомок, в кучу его
                      if (
                        targetQuestion.type !== "result" &&
                        targetQuestion.type !== null
                      ) {
                        if (!clearQuestions.includes(targetQuestion.content.id))
                          clearQuestions.push(targetQuestion.content.id);
                        getChildren(targetQuestion.content.id); //и ищем его потомков
                      }
                    }
                  });
                };
                getChildren(questionContentId);

                updateQuestion(questionId, (q) => {
                  q.content.rule.parentId === "root" ? "root" : "";
                  q.content.rule.main = [];
                  q.content.rule.children = [];
                  q.content.rule.default = "";
                });
                //чистим потомков от инфы ветвления
                await Promise.allSettled(
                  clearQuestions.map((id) => {
                    updateQuestion(id, (question) => {
                      question.content.rule.parentId = "";
                      question.content.rule.main = [];
                      question.content.rule.children = [];
                      question.content.rule.default = "";
                    });
                  }),
                );
                changeQuestionType(questionId, selectedValue);
                updateSomeWorkBackend(false);
              }}
            >
              Подтвердить
            </Button>
          </Box>
        </Box>
      </Modal>
    </>
  );
};
