import dayjs from "dayjs";
import { DatePicker } from "@mui/x-date-pickers";
import { Box, Typography } from "@mui/material";

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

import type { QuizQuestionDate } from "../../../model/questionTypes/date";
import CalendarIcon from "@icons/CalendarIcon";

type DateProps = {
  currentQuestion: QuizQuestionDate;
};

export const Date = ({ currentQuestion }: DateProps) => {
  const { answers } = useQuizViewStore();
  const answer = answers.find(
    ({ questionId }) => questionId === currentQuestion.content.id
  )?.answer as string;
  const [day, month, year] = answer?.split(".") || [];

  return (
    <Box>
      <Typography variant="h5">{currentQuestion.title}</Typography>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
          marginTop: "20px",
        }}
      >
        <DatePicker
          slots={{
            openPickerIcon: () => <CalendarIcon />,
          }}
          value={dayjs(
            answer
              ? new window.Date(`${month}.${day}.${year}`)
              : new window.Date()
          )}
          onChange={(date) => {
            if (!date) {
              return;
            }

            updateAnswer(
              currentQuestion.content.id,
              String(
                new window.Date(date.toDate()).toLocaleDateString("ru-RU", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                })
              )
            );
          }}
          slotProps={{
            openPickerButton: {
              sx: {
                p: 0,
              },
              "data-cy": "open-datepicker",
            },
          }}
          sx={{
            "& .MuiInputBase-root": {
              backgroundColor: "#F2F3F7",
              borderRadius: "10px",
              maxWidth: "250px",
              pr: "22px",
              "& input": {
                py: "11px",
                pl: "20px",
                lineHeight: "19px",
              },
              "& fieldset": {
                borderColor: "#9A9AAF",
              },
            },
          }}
        />
      </Box>
    </Box>
  );
};
