import { Select as SelectComponent } from "@/components/ViewPublicationPage/tools/Select";
import { useQuizStore } from "@/stores/useQuizStore";
import type { QuizQuestionSelect } from "@model/questionTypes/select";
import { Box, Typography, useTheme } from "@mui/material";
import { useQuizViewStore } from "@stores/quizView";
import { quizThemes } from "@utils/themes/Publication/themePublication";

type SelectProps = {
  currentQuestion: QuizQuestionSelect;
};

export const Select = ({ currentQuestion }: SelectProps) => {
  const { settings } = useQuizStore();
  const { updateAnswer, deleteAnswer } = useQuizViewStore((state) => state);
  const answers = useQuizViewStore((state) => state.answers);
  const theme = useTheme();
  const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};

  const sendSelectedAnswer = async (value: number) => {
    if (value < 0) {
      deleteAnswer(currentQuestion.id);

      return;
    }

    updateAnswer(currentQuestion.id, String(value), 0);
  };

  return (
    <Box>
      <Typography
        variant="h5"
        color={theme.palette.text.primary}
        sx={{ wordBreak: "break-word" }}
      >
        {currentQuestion.title}
      </Typography>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
          marginTop: "20px",
        }}
      >
        <SelectComponent
          placeholder={currentQuestion.content.default}
          activeItemIndex={answer ? Number(answer) : -1}
          items={currentQuestion.content.variants.map(({ answer }) => answer)}
          colorMain={theme.palette.primary.main}
          sx={{
            "& .MuiSelect-select.MuiSelect-outlined": { zIndex: 1 },
            "& .MuiOutlinedInput-notchedOutline": {
              background: settings.cfg.design
                ? quizThemes[settings.cfg.theme].isLight
                  ? "#F2F3F7"
                  : "rgba(255,255,255, 0.3)"
                : "transparent",
            },
          }}
          onChange={(_, value) => sendSelectedAnswer(value)}
        />
      </Box>
    </Box>
  );
};
