import { useQuizViewStore } from "@/stores/quizView";
import { useQuizSettings } from "@contexts/QuizDataContext";
import CalendarIcon from "@icons/CalendarIcon";
import type { QuizQuestionDate } from "@model/questionTypes/date";
import { Box, Typography, useTheme } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import type { Moment } from "moment";
import moment from "moment";

type DateProps = {
  currentQuestion: QuizQuestionDate;
};

export default ({ currentQuestion }: DateProps) => {
  const { settings } = useQuizSettings();
  const answers = useQuizViewStore((state) => state.answers);
  const { updateAnswer } = useQuizViewStore((state) => state);
  const theme = useTheme();
  const answer = answers.find(({ questionId }) => questionId === currentQuestion.id)?.answer as string;
  const currentAnswer = moment(answer) || moment();

  const onDateChange = async (date: Moment | null) => {
    if (!date) return;

    updateAnswer(currentQuestion.id, date, 0);
  };

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        width: "100%",
        marginTop: "20px",
      }}
    >
      <DatePicker
        format="DD/MM/YYYY"
        slots={{
          openPickerIcon: () => (
            <CalendarIcon
              sx={{
                "& path": { stroke: theme.palette.primary.main },
                "& rect": { stroke: theme.palette.primary.main },
              }}
            />
          ),
        }}
        value={currentAnswer}
        onChange={onDateChange}
        slotProps={{
          openPickerButton: { sx: { p: 0 }, "data-cy": "open-datepicker" },
          layout: {
            sx: { backgroundColor: theme.palette.background.default },
          },
        }}
        sx={{
          "& .MuiInputBase-root": {
            backgroundColor: settings.cfg.design
              ? quizThemes[settings.cfg.theme].isLight
                ? "#F2F3F7"
                : "rgba(154,154,175, 0.2)"
              : quizThemes[settings.cfg.theme].isLight
                ? "white"
                : theme.palette.background.default,
            borderRadius: "10px",
            maxWidth: "250px",
            pr: "30px",
            "& input": { py: "11px", pl: "20px", lineHeight: "19px" },
            "& fieldset": { borderColor: "#9A9AAF" },
          },
        }}
      />
    </Box>
  );
};
