import { useState, useRef, useEffect } from "react";
import {
  Box,
  Button,
  FormControl,
  FormControlLabel,
  Link,
  Modal,
  Radio,
  RadioGroup,
  Tooltip,
  Typography,
  useTheme,
  Checkbox,
} from "@mui/material";
import { AnyQuizQuestion, createBranchingRuleMain } from "../../../model/questionTypes/shared"
import { Select } from "../Select";

import RadioCheck from "@ui_kit/RadioCheck";
import RadioIcon from "@ui_kit/RadioIcon";
import InfoIcon from "@icons/Info";
import { DeleteIcon } from "@icons/questionsPage/deleteIcon";

import { TypeSwitch, BlockRule } from "./Settings";
import { getQuestionById, updateOpenedModalSettingsId, updateQuestion } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store";
import { enqueueSnackbar } from "notistack";


export default function BranchingQuestions() {
  const theme = useTheme();


  const { openedModalSettingsId } = useQuestionsStore();
  const [targetQuestion, setTargetQuestion] = useState<AnyQuizQuestion | null>(getQuestionById(openedModalSettingsId))
  const [parentQuestion, setParentQuestion] = useState<AnyQuizQuestion | null>(getQuestionById(openedModalSettingsId))

  if (targetQuestion === null || parentQuestion === null) {
    enqueueSnackbar("Невозможно найти данные ветвления для этого вопроса")
    return <></>
  }

  const saveData = () => {

  }

  const handleClose = () => {
    updateOpenedModalSettingsId()
  };

  return (
    <>
      <Modal open={openedModalSettingsId !== null} onClose={handleClose}>
        <Box
          sx={{
            position: "absolute",
            overflow: "hidden",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            maxWidth: "620px",
            width: "100%",
            bgcolor: "background.paper",
            borderRadius: "12px",
            boxShadow: 24,
            p: 0,
          }}
        >
          <>
            <Box
              sx={{
                boxSizing: "border-box",
                background: "#F2F3F7",
                height: "70px",
                padding: "0 25px",
                display: "flex",
                alignItems: "center",
              }}
            >
              <Box sx={{ color: "#4d4d4d" }}>
                <Typography component="span">{targetQuestion.title}</Typography>
              </Box>
              <Tooltip
                title="Настройте условия, при которых данный вопрос будет отображаться в квизе."
                placement="top"
              >
                <Box>
                  <InfoIcon />
                </Box>
              </Tooltip>
            </Box>


            <Box
              sx={{
                height: "400px",
                overflow: "auto"
              }}
            >
              {
                parentQuestion.content.rule.main.length ?
                  parentQuestion.content.rule.main.map((e: any, i: number) => {
                    if (e.next === targetQuestion.id) {
                      return <TypeSwitch key={i} targetQuestion={targetQuestion} parentQuestion={parentQuestion} ruleIndex={i} />
                    } else {
                      <></>
                    }
                  })
                  :
                  <TypeSwitch targetQuestion={targetQuestion} parentQuestion={parentQuestion} ruleIndex={0} />
              }

            </Box>


            <Box
              sx={{
                margin: "20px 0 0 20px",
                display: "flex",
                flexDirection: "column"
              }}
            >
              <Link
                variant="body2"
                sx={{
                  color: theme.palette.brightPurple.main,
                  marginBottom: "10px",
                  cursor: "pointer"
                }}
                  onClick={() => {
                    const mutate = parentQuestion
                    mutate.content.rule.main.push(createBranchingRuleMain(targetQuestion.id, parentQuestion.id))
                    setParentQuestion(mutate)
                  }}
              >
                Добавить условие
              </Link>


              <FormControlLabel control={<Checkbox

                sx={{
                  margin: 0
                }}
                checked={parentQuestion.content.rule.default === targetQuestion.id}

                onClick={() => {
                  const mutate = parentQuestion
                  mutate.content.rule.default = targetQuestion.id
                  setParentQuestion(mutate)
                }}
              />} label="Следующий вопрос по-умолчанию" />

            </Box>


            <Box sx={{ display: "flex", justifyContent: "end", gap: "10px", margin: "20px" }}>
              <Button
                variant="outlined"
                onClick={handleClose}
                sx={{ width: "100%", maxWidth: "130px" }}
              >
                Отмена
              </Button>
              <Button
                variant="contained"
                sx={{ width: "100%", maxWidth: "130px" }}
                onClick={handleClose}
              >
                Готово
              </Button>
            </Box>
          </>
        </Box>
      </Modal>
    </>
  );
}
