import {
  Box,
  Button,
  FormControlLabel,
  Modal,
  Radio,
  RadioGroup,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useQuestionsStore } from "@root/questions/store";
import { AnyTypedQuizQuestion } from "@frontend/squzanswerer";
import { useUiTools } from "@root/uiTools/store";
import { setModalQuestionTargetContentId, setOpenedModalQuestions } from "@root/uiTools/actions";
import React, { useEffect, useState } from "react";
import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";
import { RoundedCheckedIcon } from "@icons/questionsPage/RoundedCheckedIcon";

export const BranchingQuestionsModal = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(650));

  const trashQuestions = useQuestionsStore().questions;
  const questions = trashQuestions.filter((question) => question.type !== "result");

  const openedModalQuestions = useUiTools((state) => state.openedModalQuestions);

  const handleClose = () => {
    setOpenedModalQuestions(false);
  };

  const typedQuestions: AnyTypedQuizQuestion[] = questions.filter(
    (question) => question.type && question.type !== "result"
  ) as AnyTypedQuizQuestion[];

  if (typedQuestions.length === 0) return <></>;

  const [selectedQuestion, setSelectedQuestion] = useState<string | null>(null);

  useEffect(() => {
    if (openedModalQuestions) {
      setSelectedQuestion(null);
    }
  }, [openedModalQuestions]);

  const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedQuestion(event.target.value);
  };

  const handleConfirm = () => {
    if (selectedQuestion) {
      setModalQuestionTargetContentId(selectedQuestion);
    }
    handleClose();
  };

  return (
    <Modal
      open={openedModalQuestions}
      onClose={handleClose}
    >
      <Box
        sx={{
          position: "absolute",
          overflow: "auto",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          maxWidth: "620px",
          width: "90%",
          bgcolor: "background.paper",
          borderRadius: "12px",
          boxShadow: 24,
        }}
      >
        <Box sx={{ width: "100%", background: theme.palette.background.default }}>
          <Typography
            sx={{
              padding: "25px 0 25px 20px",
              color: theme.palette.grey2.main,
            }}
          >
            Выберите вопрос, который вы хотите добавить в ветвление
          </Typography>
        </Box>
        <RadioGroup
          value={selectedQuestion}
          onChange={handleRadioChange}
          sx={{
            height: "346px",
            width: "100%",
            overflow: "auto",
            display: "flex",
            flexDirection: "column",
            flexWrap: "nowrap",
          }}
        >
          {typedQuestions.map((question, index) => (
            <FormControlLabel
              key={question.content.id}
              value={question.content.id}
              control={
                <Radio
                  checkedIcon={<RadioCheck />}
                  icon={question.content.rule.parentId ? <RoundedCheckedIcon /> : <RadioIcon />}
                />
              }
              label={question.title || "нет заголовка"}
              disabled={!!question.content.rule.parentId}
              sx={{
                padding: "8px 12px",
                margin: 0,
                width: "100%",
                backgroundColor: index % 2 === 0 ? theme.palette.common.white : "rgba(242, 243, 247, 0.5)",
                color: theme.palette.grey3.main,
              }}
            />
          ))}
        </RadioGroup>
        <Box
          sx={{
            margin: "20px",
            width: "auto",
            display: "flex",
            justifyContent: isMobile ? "space-between" : "end",
            gap: "10px",
          }}
        >
          <Button
            sx={{ width: isMobile ? "150px" : "130px", height: "44px" }}
            onClick={handleClose}
            variant={"outlined"}
          >
            Отмена
          </Button>

          <Button
            sx={{ width: isMobile ? "150px" : "130px", height: "44px" }}
            variant={"contained"}
            onClick={handleConfirm}
          >
            Готово
          </Button>
        </Box>
      </Box>
    </Modal>
  );
};
