import { DeleteIcon } from "@icons/questionsPage/deleteIcon";
import type { SxProps } from "@mui/material";
import { Box, Button, IconButton, Modal, Typography, useMediaQuery, useTheme } from "@mui/material";
import { copyQuestion, deleteQuestion, deleteQuestionWithTimeout } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { updateDesireToOpenABranchingModal } from "@root/uiTools/actions";
import MiniButtonSetting from "@ui_kit/MiniButtonSetting";
import { DeleteFunction } from "@utils/deleteFunc";
import { memo, useState } from "react";
import { CopyIcon } from "../../assets/icons/questionsPage/CopyIcon";
import Branching from "../../assets/icons/questionsPage/branching";
import SettingIcon from "../../assets/icons/questionsPage/settingIcon";
import { QuestionType } from "@model/question/question";
import type { AnyTypedQuizQuestion } from "@frontend/squzanswerer";

interface Props {
  switchState: string;
  SSHC: (data: string) => void;
  questionId: string;
  questionContentId: string;
  questionType: QuestionType;
  questionHasParent: boolean;
  setOpenBranchingPage: (a: boolean) => void;
  sx?: SxProps;
}

const ButtonsOptions = memo<Props>(function ({
  SSHC,
  switchState,
  questionId,
  questionContentId,
  questionType,
  questionHasParent,
  setOpenBranchingPage,
}) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const isWrappMiniButtonSetting = useMediaQuery(theme.breakpoints.down(920));
  const quiz = useCurrentQuiz();
  const [openDelete, setOpenDelete] = useState<boolean>(false);
  const isQuestionFirst = useQuestionsStore((state) => state.questions[0]?.id === questionId);

  if (!quiz) return null;

  const openedModal = () => {
    setOpenBranchingPage(true);
    updateDesireToOpenABranchingModal(questionContentId);
  };

  const buttonSetting: {
    icon: JSX.Element;
    title: string;
    value: string;
    myFunc?: any;
  }[] = [
    {
      icon: <SettingIcon color={switchState === "setting" ? "#ffffff" : theme.palette.grey3.main} />,
      title: "Настройки",
      value: "setting",
    },
    {
      icon: <Branching color={switchState === "branching" ? "#ffffff" : theme.palette.grey3.main} />,
      title: "Ветвление",
      value: "branching",
      myFunc: (question: AnyTypedQuizQuestion) => {
        setOpenBranchingPage(true);
        updateDesireToOpenABranchingModal(question.content.id);
      },
    },
  ];

  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        background: "#f2f3f7",
        height: isMobile ? "92px" : "70px",
      }}
    >
      <Box
        sx={{
          padding: isMobile ? " 3px 12px 11px" : "20px",
          display: "flex",
          flexWrap: isMobile ? "wrap" : "nowrap",
          gap: "6px",
        }}
      >
        {buttonSetting.map(({ icon, title, value, myFunc }) => (
          <Box key={value}>
            {value === "branching" ? (
              ["page", "text", "date", "number"].includes(questionType) ? null : (
                <MiniButtonSetting
                  key={title}
                  onClick={() => {
                    openedModal();
                  }}
                  sx={{
                    display: quiz.config.type === "form" ? "none" : "flex",
                    backgroundColor: switchState === value ? theme.palette.brightPurple.main : "transparent",
                    color: switchState === value ? "#ffffff" : theme.palette.grey3.main,
                    minWidth: isWrappMiniButtonSetting ? "30px" : "64px",
                    height: "30px",
                    "&:hover": {
                      color: theme.palette.grey3.main,
                      "& path": { stroke: theme.palette.grey3.main },
                    },
                  }}
                >
                  {icon}
                  {isWrappMiniButtonSetting ? null : title}
                </MiniButtonSetting>
              )
            ) : (
              <MiniButtonSetting
                key={title}
                onClick={() => {
                  SSHC(value);
                  myFunc();
                }}
                sx={{
                  backgroundColor: switchState === value ? theme.palette.brightPurple.main : "transparent",
                  color: switchState === value ? "#ffffff" : theme.palette.grey3.main,
                  minWidth: isWrappMiniButtonSetting ? "30px" : "64px",
                  height: "30px",
                  "&:hover": {
                    color: theme.palette.grey3.main,
                    "& path": { stroke: theme.palette.grey3.main },
                  },
                }}
              >
                {icon}
                {isWrappMiniButtonSetting ? null : title}
              </MiniButtonSetting>
            )}
          </Box>
        ))}
      </Box>
      <Box
        sx={{
          padding: "20px",
          display: "flex",
          gap: "6px",
        }}
      >
        <IconButton
          sx={{ borderRadius: "6px", padding: "2px" }}
          onClick={() => copyQuestion(questionId, quiz.backendId)}
        >
          <CopyIcon color={"#4D4D4D"} />
        </IconButton>
        {(quiz?.config.type !== "form" || !isQuestionFirst) && (
          <IconButton
            sx={{ borderRadius: "6px", padding: "2px" }}
            onClick={() => {
              if (questionType === null) {
                deleteQuestion(questionId);
              }
              if (questionHasParent) {
                setOpenDelete(true);
              } else {
                deleteQuestionWithTimeout(questionId, () => DeleteFunction(questionId));
              }
            }}
            data-cy="delete-question"
          >
            <DeleteIcon color={"#4D4D4D"} />
          </IconButton>
        )}
        <Modal
          open={openDelete}
          onClose={() => setOpenDelete(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" }}
            >
              Вы удаляете вопрос, участвующий в ветвлении. Все его потомки потеряют данные ветвления. Вы уверены, что
              хотите удалить вопрос?
            </Typography>
            <Box
              sx={{
                marginTop: "30px",
                display: "flex",
                justifyContent: "center",
                gap: "15px",
              }}
            >
              <Button
                variant="contained"
                sx={{ minWidth: "150px" }}
                onClick={() => setOpenDelete(false)}
              >
                Отмена
              </Button>
              <Button
                variant="contained"
                sx={{ minWidth: "150px" }}
                onClick={() => {
                  deleteQuestionWithTimeout(questionId, () => DeleteFunction(questionId));
                }}
              >
                Подтвердить
              </Button>
            </Box>
          </Box>
        </Modal>
      </Box>
    </Box>
  );
});

ButtonsOptions.displayName = "ButtonsOptions";

export default ButtonsOptions;
