import { useLayoutEffect, useState } from "react";
import { Box, Typography } from "@mui/material";

import { CustomSlider } from "@ui_kit/CustomSlider";

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

interface Props {
  question: QuizQuestionNumber;
}

export default function Number({ question }: Props) {
  const [sliderValues, setSliderValues] = useState<number | number[]>(0);

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

  useLayoutEffect(() => {
    if (question.content.chooseRange) {
      setSliderValues([start, start + (max - start) / 2]);
    } else {
      setSliderValues(start);
    }
  }, [max, question.content.chooseRange, start]);

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        gap: 1,
      }}
    >
      <Typography variant="h6" data-cy="question-title">{question.title}</Typography>
      <Box
        sx={{
          px: 2,
        }}
      >
        <CustomSlider
          value={sliderValues}
          onChange={(value) => setSliderValues(value)}
          min={min}
          max={max}
          defaultValue={start}
          step={question.content.step}
        />
      </Box>
    </Box>
  );
}
