import { useState, useRef, useEffect } from "react";
import { useParams } from "react-router-dom";
import {
  Box,
  Button,
  Chip,
  FormControl,
  FormControlLabel,
  IconButton,
  Link,
  Modal,
  Radio,
  RadioGroup,
  Typography,
  useTheme,
} from "@mui/material";
import { questionStore, resetSomeField, updateQuestionsList } from "@root/questions";
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";

type BranchingQuestionsProps = {
  totalIndex: number;
};

const ACTIONS = ["Показать", "Скрыть"];
const STIPULATIONS = ["Условие 1", "Условие 2", "Условие 3"];
const ANSWERS = ["Ответ 1", "Ответ 2", "Ответ 3"];
const CONDITIONS = ["Все условия обязательны", "Обязательно хотя бы одно условие"];

export default function BranchingQuestions({ totalIndex }: BranchingQuestionsProps) {
  const [title, setTitle] = useState<string>("Заголовок вопроса");
  const [titleInputWidth, setTitleInputWidth] = useState<number>(0);
  const quizId = Number(useParams().quizId);
  const { openedModalSettings, listQuestions } = questionStore();
  const theme = useTheme();
  const titleRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setTitleInputWidth(titleRef.current?.offsetWidth || 0);
  }, [title]);

  const handleClose = () => {
    resetSomeField({ openedModalSettings: "" });
  };

  return (
    <>
      <Modal
        open={Boolean(openedModalSettings)}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box
          sx={{
            position: "absolute" as "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",
              padding: "25px",
              height: "70px",
              display: "flex",
            }}
          >
            <Box sx={{ color: "#9A9AAF" }}>
              <Typography component="span">(</Typography>
              <Box sx={{ display: "inline" }}>
                <Typography
                  ref={titleRef}
                  sx={{
                    position: "absolute",
                    opacity: 0,
                    zIndex: "-100",
                    whiteSpace: "pre",
                  }}
                >
                  {title}
                </Typography>
                <input
                  type="text"
                  value={title}
                  onChange={({ target }) => setTitle(target.value)}
                  style={{
                    width: titleInputWidth,
                    outline: "none",
                    background: "transparent",
                    border: "none",
                    fontSize: "18px",
                    minWidth: "160px",
                    maxWidth: "500px",
                  }}
                />
              </Box>
              <Typography component="span">)</Typography>
            </Box>
            <InfoIcon width={24} height={24} />
          </Box>
          <Box
            sx={{
              padding: "20px",
              display: "flex",
              flexDirection: "column",
              gap: "30px",
            }}
          >
            <Box
              sx={{
                display: "flex",
                gap: "20px",
                alignItems: "center",
              }}
            >
              <Select
                items={ACTIONS}
                activeItemIndex={listQuestions[quizId][totalIndex].content.rule.show ? 0 : 1}
                sx={{ maxWidth: "140px" }}
                onChange={(action) => {
                  const clonContent = listQuestions[quizId][totalIndex].content;
                  clonContent.rule.show = action === ACTIONS[0];
                  updateQuestionsList(quizId, totalIndex, {
                    content: clonContent,
                  });
                }}
              />
              <Typography sx={{ color: theme.palette.grey2.main }}>если в ответе на вопрос</Typography>
            </Box>
            {listQuestions[quizId][totalIndex].content.rule.reqs.map((request, index) => (
              <Box
                key={index}
                sx={{
                  padding: "20px",
                  borderRadius: "8px",
                  height: "100%",
                  bgcolor: "#F2F3F7",
                }}
              >
                <Box
                  sx={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    pb: "5px",
                  }}
                >
                  <Typography sx={{ color: "#4D4D4D", fontWeight: "500" }}>Условие 1</Typography>
                  <IconButton
                    sx={{ borderRadius: "6px", padding: "2px" }}
                    onClick={() => {
                      const clonContent = listQuestions[quizId][totalIndex].content;

                      clonContent.rule.reqs.splice(index, 1);
                      updateQuestionsList(quizId, totalIndex, {
                        content: clonContent,
                      });
                    }}
                  >
                    <DeleteIcon style={{ color: "#4D4D4D" }} />
                  </IconButton>
                </Box>
                <Select
                  empty
                  activeItemIndex={request.id ? Number(request.id) : -1}
                  items={STIPULATIONS}
                  onChange={(stipulation) => {
                    const clonContent = listQuestions[quizId][totalIndex].content;

                    clonContent.rule.reqs[index] = {
                      id: String(STIPULATIONS.findIndex((item) => item.includes(stipulation))),
                      vars: request.vars,
                    };

                    updateQuestionsList(quizId, totalIndex, {
                      content: clonContent,
                    });
                  }}
                  sx={{ marginBottom: "15px" }}
                />
                {request.id && (
                  <>
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        pb: "10px",
                      }}
                    >
                      <Typography sx={{ color: "#4D4D4D", fontWeight: "500" }}>Дан ответ</Typography>
                      <Typography sx={{ color: "#7E2AEA", pl: "10px" }}>
                        (Укажите один или несколько вариантов)
                      </Typography>
                    </Box>
                    <Select
                      empty
                      activeItemIndex={-1}
                      items={ANSWERS}
                      onChange={(answer) => {
                        const clonContent = listQuestions[quizId][totalIndex].content;
                        const answerItemIndex = ANSWERS.findIndex((answerItem) => answerItem === answer);

                        if (!clonContent.rule.reqs[index].vars.includes(answerItemIndex)) {
                          listQuestions[quizId][totalIndex].content.rule.reqs[index].vars.push(answerItemIndex);
                        }

                        updateQuestionsList(quizId, totalIndex, {
                          content: clonContent,
                        });
                      }}
                      sx={{
                        marginBottom: "10px",
                        ".MuiSelect-select.MuiInputBase-input": {
                          color: "transparent",
                        },
                      }}
                    />
                    <Box
                      sx={{
                        display: "flex",
                        gap: "10px",
                      }}
                    >
                      {listQuestions[quizId][totalIndex].content.rule.reqs[index].vars.map((item, varIndex) => (
                        <Chip
                          key={varIndex}
                          label={ANSWERS[item]}
                          variant="outlined"
                          onDelete={() => {
                            const clonContent = listQuestions[quizId][totalIndex].content;
                            const removedItemIndex = clonContent.rule.reqs[index].vars.findIndex(
                              (varItem) => varItem === item
                            );

                            clonContent.rule.reqs[index].vars.splice(removedItemIndex, 1);

                            updateQuestionsList(quizId, totalIndex, {
                              content: clonContent,
                            });
                          }}
                        />
                      ))}
                    </Box>
                  </>
                )}
              </Box>
            ))}
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "baseline",
              }}
            >
              <Link
                variant="body2"
                sx={{
                  color: theme.palette.brightPurple.main,
                  marginBottom: "10px",
                }}
                onClick={() => {
                  const clonContent = listQuestions[quizId][totalIndex].content;
                  clonContent.rule.reqs.push({ id: "", vars: [] });
                  updateQuestionsList(quizId, totalIndex, {
                    content: clonContent,
                  });
                }}
              >
                Добавить условие
              </Link>
              <FormControl>
                <RadioGroup
                  aria-labelledby="demo-controlled-radio-buttons-group"
                  value={listQuestions[quizId][totalIndex].content.rule.or ? 1 : 0}
                  onChange={(_, value) => {
                    const clonContent = listQuestions[quizId][totalIndex].content;
                    clonContent.rule.or = Boolean(Number(value));
                    updateQuestionsList(quizId, totalIndex, {
                      content: clonContent,
                    });
                  }}
                >
                  {CONDITIONS.map((condition, index) => (
                    <FormControlLabel
                      key={index}
                      sx={{ color: theme.palette.grey2.main }}
                      value={index}
                      control={<Radio checkedIcon={<RadioCheck />} icon={<RadioIcon />} />}
                      label={condition}
                    />
                  ))}
                </RadioGroup>
              </FormControl>
            </Box>
            <Box sx={{ display: "flex", justifyContent: "end", gap: "10px" }}>
              <Button variant="outlined" onClick={handleClose} sx={{ width: "100%", maxWidth: "130px" }}>
                Отмена
              </Button>
              <Button variant="contained" sx={{ width: "100%", maxWidth: "130px" }} onClick={handleClose}>
                Готово
              </Button>
            </Box>
          </Box>
        </Box>
      </Modal>
    </>
  );
}
