import { useEffect } from "react";
import { Box, Typography, Slider, useTheme } from "@mui/material";

import CustomTextField from "@ui_kit/CustomTextField";

import { useQuizViewStore, updateAnswer } from "@root/quizView";

import type { QuizQuestionNumber } from "../../../model/questionTypes/number";

type NumberProps = {
  stepNumber: number;
  question: QuizQuestionNumber;
};

export const Number = ({ stepNumber, question }: NumberProps) => {
  const theme = useTheme();
  const { answers } = useQuizViewStore();
  const { answer } = answers.find(({ step }) => step === stepNumber) ?? {};

  const min = window.Number(question.content.range.split("—")[0]);
  const max = window.Number(question.content.range.split("—")[1]);

  useEffect(() => {
    if (!answer) {
      updateAnswer(stepNumber, "1");
    }
  }, []);

  return (
    <Box>
      <Typography variant="h5">{question.title}</Typography>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
          marginTop: "20px",
        }}
      >
        <CustomTextField
          placeholder="0"
          value={answer || ""}
          onChange={({ target }) => {
            updateAnswer(
              stepNumber,
              window.Number(target.value) > max
                ? String(max)
                : window.Number(target.value) < min
                ? String(min)
                : target.value
            );
          }}
          sx={{
            maxWidth: "80px",
            "& .MuiInputBase-input": { textAlign: "center" },
          }}
        />
        <Slider
          value={window.Number(answer || 1)}
          min={min}
          max={max}
          step={question.content.step || 1}
          sx={{
            color: theme.palette.brightPurple.main,
            padding: "0",
            marginTop: "25px",
          }}
          onChange={(_, value) => {
            updateAnswer(stepNumber, String(value));
          }}
        />
      </Box>
    </Box>
  );
};
