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

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

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

import { sendAnswer } from "@api/quizRelase";
import { enqueueSnackbar } from "notistack";
import { useQuizId } from "../../../contexts/QuizIdContext";
import type { QuizQuestionSelect } from "../../../model/questionTypes/select";

type SelectProps = {
    currentQuestion: QuizQuestionSelect;
};

export const Select = ({ currentQuestion }: SelectProps) => {
    const theme = useTheme();
    const qid = useQuizId();
    const { answers } = useQuizViewStore();
    const { answer } =
        answers.find(
            ({ questionId }) => questionId === currentQuestion.id
        ) ?? {};

    return (
        <Box>
            <Typography variant="h5" color={theme.palette.text.primary}>{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}
                    onChange={async (_, value) => {
                        if (value < 0) {
                            deleteAnswer(currentQuestion.id);
                            try {

                                await sendAnswer({
                                    questionId: currentQuestion.id,
                                    body: "",
                                    qid,
                                });

                            } catch (e) {
                                enqueueSnackbar("ответ не был засчитан");
                            }
                            return;
                        }

                        try {

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

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

                        } catch (e) {
                            enqueueSnackbar("ответ не был засчитан");
                        }


                    }}
                />
            </Box>
        </Box>
    );
};
