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

import { Select as SelectComponent } from "../tools//Select";

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

import { sendAnswer } from "@api/quizRelase";
import { enqueueSnackbar } from "notistack";
import type { QuizQuestionSelect } from "../../../model/questionTypes/select";
import { useQuizData } from "@contexts/QuizDataContext";
import { useState } from "react";
import { quizThemes } from "@utils/themes/Publication/themePublication";

type SelectProps = {
  currentQuestion: QuizQuestionSelect;
};

export const Select = ({ currentQuestion }: SelectProps) => {
  const theme = useTheme();
  const { quizId, settings } = useQuizData();
  const [isSending, setIsSending] = useState<boolean>(false);
  const { answers } = useQuizViewStore();
  const { answer } =
    answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};

  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
          disabled={isSending}
          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(154,154,175, 0.2)"
                : "transparent",
            },
          }}
          onChange={async (_, value) => {
            setIsSending(true);
            if (value < 0) {
              deleteAnswer(currentQuestion.id);
              try {
                await sendAnswer({
                  questionId: currentQuestion.id,
                  body: "",
                  qid: quizId,
                });
              } catch (e) {
                enqueueSnackbar("ответ не был засчитан");
              }
              return setIsSending(false);
            }

            try {
              await sendAnswer({
                questionId: currentQuestion.id,
                body: String(
                  currentQuestion.content.variants[Number(value)].answer
                ),
                qid: quizId,
              });

              updateAnswer(currentQuestion.id, String(value), 0);
            } catch (e) {
              enqueueSnackbar("ответ не был засчитан");
            }

            setIsSending(false);
          }}
        />
      </Box>
    </Box>
  );
};
