import { useParams } from "react-router-dom";
import {
  Box,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  Typography,
  Tooltip,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { useDebouncedCallback } from "use-debounce";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
import CustomTextField from "@ui_kit/CustomTextField";

import { questionStore, updateQuestionsList } from "@root/questions";

import CheckedIcon from "@ui_kit/RadioCheck";
import CheckIcon from "@ui_kit/RadioIcon";
import InfoIcon from "../../../assets/icons/InfoIcon";

import type { QuizQuestionText } from "../../../model/questionTypes/text";

type SettingTextFieldProps = {
  totalIndex: number;
};

type Answer = {
  name: string;
  value: "single" | "multi" | "number";
};

const ANSWER_TYPES: Answer[] = [
  { name: "Однострочное", value: "single" },
  { name: "Многострочное", value: "multi" },
  { name: "Только числа", value: "number" },
];

export default function SettingTextField({
  totalIndex,
}: SettingTextFieldProps) {
  const { listQuestions } = questionStore();
  const quizId = Number(useParams().quizId);
  const theme = useTheme();
  const isWrapperColumn = useMediaQuery(theme.breakpoints.down(980));
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const question = listQuestions[quizId][totalIndex] as QuizQuestionText;
  const debounced = useDebouncedCallback((value) => {
    updateQuestionsList(quizId, totalIndex, {
      content: { ...question.content, innerName: value },
    });
  }, 1000);

  return (
    <Box
      sx={{
        display: "flex",
        justifyContent: "space-between",
        flexDirection: isWrapperColumn ? "column" : null,
        marginRight: isMobile ? "0px" : "50px",
      }}
    >
      <Box sx={{ padding: "20px" }}>
        <Typography>Настройки ответов</Typography>
        <FormControl>
          <RadioGroup
            aria-labelledby="demo-controlled-radio-buttons-group"
            name="controlled-radio-buttons-group"
            value={ANSWER_TYPES.findIndex(({ value }) => {
              switch (value) {
                case "multi":
                  return value === "multi";

                case "number":
                  return value === "number";

                case "single":
                  return value === "single";

                default:
                  return false;
              }
            })}
            onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
              const clonedContent = {
                ...question.content,
                single: false,
                multi: false,
                number: false,
                [ANSWER_TYPES[Number(target.value)].value]: true,
              };

              updateQuestionsList(quizId, totalIndex, { content: clonedContent });
            }}
          >
            {ANSWER_TYPES.map(({ name }, index) => (
              <FormControlLabel
                key={index}
                sx={{
                  color: theme.palette.grey2.main,
                  "& .MuiRadio-root": { padding: "8px 9px" },
                }}
                value={index}
                control={
                  <Radio icon={<CheckIcon />} checkedIcon={<CheckedIcon />} />
                }
                label={name}
              />
            ))}
          </RadioGroup>
        </FormControl>
      </Box>
      <Box sx={{ padding: "20px", display: "flex", flexDirection: "column" }}>
        <Typography>Настройки вопросов</Typography>
        <CustomCheckbox
          sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
          label={"Автозаполнение адреса"}
          checked={question.content.autofill}
          handleChange={({ target }) => {
            updateQuestionsList(quizId, totalIndex, {
              content: { ...question.content, autofill: target.checked },
            });
          }}
        />
        <CustomCheckbox
          sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
          label={"Необязательный вопрос"}
          checked={!question.required}
          handleChange={(e) => {
            updateQuestionsList(quizId, totalIndex, {
              required: !e.target.checked,
            });
          }}
        />
        <Box
          sx={{
            width: isMobile ? "90%" : "auto",
            display: "flex",
            alignItems: "center",
          }}
        >
          <CustomCheckbox
            sx={{ display: "block", mr: isMobile ? "0px" : "16px" }}
            label={"Внутреннее название вопроса"}
            checked={question.content.innerNameCheck}
            handleChange={({ target }) => {
              updateQuestionsList(quizId, totalIndex, {
                content: {
                  ...question.content,
                  innerNameCheck: target.checked,
                  innerName: target.checked ? question.content.innerName : "",
                },
              });
            }}
          />
          <Tooltip
            title="Будет отображаться как заголовок вопроса в приходящих заявках."
            placement="top"
          >
            <Box>
              <InfoIcon />
            </Box>
          </Tooltip>
        </Box>
        {question.content.innerNameCheck && (
          <CustomTextField
            placeholder={"Развёрнутое описание вопроса"}
            text={question.content.innerName}
            onChange={({ target }) => debounced(target.value)}
          />
        )}
      </Box>
    </Box>
  );
}
