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

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

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

import type { QuizQuestionSelect } from "../../../model/questionTypes/select";
import { enqueueSnackbar } from "notistack";
import { sendAnswer } from "@api/quizRelase";
import { useQuizData } from "@utils/hooks/useQuizData";

type SelectProps = {
    currentQuestion: QuizQuestionSelect;
};

export const Select = ({ currentQuestion }: SelectProps) => {
    const theme = useTheme();

    const { settings } = useQuizData();
    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: settings.qid
                                });

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

                        try {

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

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

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


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