import { useState } from "react";
import { useParams } from "react-router-dom";
import {
  Box,
  Typography,
  Popper,
  Grow,
  Paper,
  MenuList,
  MenuItem,
  ClickAwayListener,
  Modal,
  Button,
  useTheme,
} from "@mui/material";

import {
  questionStore,
  updateQuestionsList,
  removeQuestionForce,
  createQuestion,
} from "@root/questions";
import { BUTTON_TYPE_QUESTIONS } from "../TypeQuestions";

import type { RefObject } from "react";
import type {
  QuizQuestionType,
  QuizQuestionBase,
} from "../../../model/questionTypes/shared";

type ChooseAnswerModalProps = {
  open: boolean;
  onClose: () => void;
  anchorRef: RefObject<HTMLDivElement>;
  totalIndex: number;
  switchState: string;
};

export const ChooseAnswerModal = ({
  open,
  onClose,
  anchorRef,
  totalIndex,
  switchState,
}: ChooseAnswerModalProps) => {
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [selectedValue, setSelectedValue] = useState<QuizQuestionType>("text");
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();
  const theme = useTheme();

  return (
    <>
      <Popper
        placement="right-start"
        open={open}
        anchorEl={anchorRef.current}
        transition
      >
        {({ 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 !== switchState && {
                        onClick: () => {
                          onClose();
                          setOpenModal(true);
                          setSelectedValue(value);
                        },
                      })}
                    >
                      <Box>{icon}</Box>
                      <Typography
                        sx={{
                          color:
                            value === switchState
                              ? 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">
            Все настройки, кроме заголовка вопроса будут сброшены
          </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={() => {
                setOpenModal(false);

                const question = listQuestions[quizId][totalIndex];

                removeQuestionForce(quizId, totalIndex);
                createQuestion(quizId, selectedValue, totalIndex);
                updateQuestionsList<QuizQuestionBase>(quizId, totalIndex, {
                  expanded: question.expanded,
                });
              }}
            >
              Подтвердить
            </Button>
          </Box>
        </Box>
      </Modal>
    </>
  );
};
