import { useState } from "react";
import { useParams } from "react-router-dom";
import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
import ButtonsOptions from "../ButtonsOptions";
import CustomNumberField from "@ui_kit/CustomNumberField";
import SwitchSlider from "./switchSlider";
import { questionStore, updateQuestionsList } from "@root/questions";

interface Props {
  totalIndex: number;
}

export default function SliderOptions({ totalIndex }: Props) {
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(980));
  const isMobile = useMediaQuery(theme.breakpoints.down(790));
  const [switchState, setSwitchState] = useState("setting");
  const [stepError, setStepError] = useState("");
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();

  const SSHC = (data: string) => {
    setSwitchState(data);
  };

  return (
    <>
      <Box
        sx={{
          width: isTablet ? "auto" : "100%",
          maxWidth: "673.8px",
          display: "flex",
          pl: "20px",
          pr: "20px",
          pb: isMobile ? "30px" : "20px",
          flexDirection: "column",
          gap: "20px",
        }}
      >
        <Box sx={{ gap: "14px", display: "flex", flexDirection: "column" }}>
          <Typography sx={{ fontWeight: "500", fontSize: "18px", color: "#4D4D4D" }}>
            Выбор значения из диапазона
          </Typography>
          <Box sx={{ width: "100%", display: "flex", alignItems: "center", gap: "20px" }}>
            <CustomNumberField
              sx={{ maxWidth: "310px", width: "100%" }}
              placeholder={"0"}
              min={0}
              max={99}
              value={
                listQuestions[quizId][totalIndex].content.range.split("—")[0]
              }
              onChange={({ target }) => {
                const clonContent = listQuestions[quizId][totalIndex].content;
                clonContent.range = `${target.value}—${
                  listQuestions[quizId][totalIndex].content.range.split("—")[1]
                }`;
                updateQuestionsList(quizId, totalIndex, {
                  content: clonContent,
                });
              }}
              onBlur={({ target }) => {
                const start = listQuestions[quizId][totalIndex].content.start;
                const min = Number(target.value);
                const max = Number(
                  listQuestions[quizId][totalIndex].content.range.split("—")[1]
                );

                if (min >= max) {
                  const clonContent = listQuestions[quizId][totalIndex].content;
                  clonContent.range = `${max - 1 >= 0 ? max - 1 : 0}—${
                    listQuestions[quizId][totalIndex].content.range.split(
                      "—"
                    )[1]
                  }`;
                  updateQuestionsList(quizId, totalIndex, {
                    content: clonContent,
                  });
                }

                if (start < min) {
                  updateQuestionsList(quizId, totalIndex, {
                    content: {
                      ...listQuestions[quizId][totalIndex].content,
                      start: min,
                    },
                  });
                }
              }}
            />
            <Typography>—</Typography>
            <CustomNumberField
              sx={{ maxWidth: "310px", width: "100%" }}
              placeholder={"100"}
              min={0}
              max={100}
              value={
                listQuestions[quizId][totalIndex].content.range.split("—")[1]
              }
              onChange={({ target }) => {
                const clonContent = listQuestions[quizId][totalIndex].content;
                clonContent.range = `${
                  listQuestions[quizId][totalIndex].content.range.split("—")[0]
                }—${target.value}`;
                updateQuestionsList(quizId, totalIndex, {
                  content: clonContent,
                });
              }}
              onBlur={({ target }) => {
                const start = listQuestions[quizId][totalIndex].content.start;
                const step = listQuestions[quizId][totalIndex].content.step;
                const min = Number(
                  listQuestions[quizId][totalIndex].content.range.split("—")[0]
                );
                const max = Number(target.value);
                const range = max - min;

                if (max <= min) {
                  const clonContent = listQuestions[quizId][totalIndex].content;
                  clonContent.range = `${
                    listQuestions[quizId][totalIndex].content.range.split(
                      "—"
                    )[0]
                  }—${min + 1 >= 100 ? 100 : min + 1}`;
                  updateQuestionsList(quizId, totalIndex, {
                    content: clonContent,
                  });
                }

                if (start > max) {
                  updateQuestionsList(quizId, totalIndex, {
                    content: {
                      ...listQuestions[quizId][totalIndex].content,
                      start: max,
                    },
                  });
                }

                if (step > max) {
                  updateQuestionsList(quizId, totalIndex, {
                    content: {
                      ...listQuestions[quizId][totalIndex].content,
                      step: max,
                    },
                  });

                  if (range % step) {
                    setStepError(
                      `Шаг должен делить без остатка диапазон ${max} - ${min} = ${
                        max - min
                      }`
                    );
                  } else {
                    setStepError("");
                  }
                }
              }}
            />
          </Box>
        </Box>
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            flexDirection: isMobile ? "column-reverse" : "",
            gap: isMobile ? "15px" : "50px",
          }}
        >
          <Box sx={{ width: "100%" }}>
            <Typography sx={{ fontWeight: "500", fontSize: "18px", color: "#4D4D4D", mb: "14px" }}>
              Начальное значение
            </Typography>
            <CustomNumberField
              sx={{ maxWidth: "310px", width: "100%" }}
              placeholder={"50"}
              min={Number(
                listQuestions[quizId][totalIndex].content.range.split("—")[0]
              )}
              max={Number(
                listQuestions[quizId][totalIndex].content.range.split("—")[1]
              )}
              value={String(listQuestions[quizId][totalIndex].content.start)}
              onChange={({ target }) => {
                const clonContent = listQuestions[quizId][totalIndex].content;
                clonContent.start = Number(target.value);
                updateQuestionsList(quizId, totalIndex, {
                  content: clonContent,
                });
              }}
            />
          </Box>
          <Box sx={{ width: "100%" }}>
            <Typography
              sx={{
                fontWeight: "500",
                fontSize: "18px",
                color: "#4D4D4D",
                mb: "10px",
              }}
            >
              Шаг
            </Typography>
            <CustomNumberField
              sx={{ maxWidth: "310px", width: "100%" }}
              min={0}
              max={100}
              placeholder={"1"}
              error={stepError}
              value={String(listQuestions[quizId][totalIndex].content.step)}
              onChange={({ target }) => {
                const clonContent = listQuestions[quizId][totalIndex].content;
                clonContent.step = Number(target.value);
                updateQuestionsList(quizId, totalIndex, {
                  content: clonContent,
                });
              }}
              onBlur={({ target }) => {
                const min = Number(
                  listQuestions[quizId][totalIndex].content.range.split("—")[0]
                );
                const max = Number(
                  listQuestions[quizId][totalIndex].content.range.split("—")[1]
                );
                const range = max - min;
                const step = Number(target.value);

                if (step > max) {
                  updateQuestionsList(quizId, totalIndex, {
                    content: {
                      ...listQuestions[quizId][totalIndex].content,
                      step: max,
                    },
                  });
                }

                if (range % step) {
                  setStepError(
                    `Шаг должен делить без остатка диапазон ${max} - ${min} = ${
                      max - min
                    }`
                  );
                } else {
                  setStepError("");
                }
              }}
            />
          </Box>
        </Box>
      </Box>
      <ButtonsOptions
        switchState={switchState}
        SSHC={SSHC}
        totalIndex={totalIndex}
      />
      <SwitchSlider switchState={switchState} totalIndex={totalIndex} />
    </>
  );
}
