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

import CustomTextField from "@ui_kit/CustomTextField";

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

import { sendAnswer } from "@api/quizRelase";
import { enqueueSnackbar } from "notistack";
import { useDebouncedCallback } from "use-debounce";
import { useQuizId } from "../../../contexts/QuizIdContext";
import type { QuizQuestionText } from "../../../model/questionTypes/text";

type TextProps = {
    currentQuestion: QuizQuestionText;
};

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

    const inputHC = useDebouncedCallback(async (text) => {
        try {

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


        } catch (e) {
            enqueueSnackbar("ответ не был засчитан");
        }
    }, 400);
    return (
        <Box>
            <Typography variant="h5" color={theme.palette.text.primary}>{currentQuestion.title}</Typography>
            <Box
                sx={{
                    display: "flex",
                    flexDirection: "column",
                    width: "100%",
                    marginTop: "20px",
                }}
            >
                <CustomTextField
                    placeholder={currentQuestion.content.placeholder}
                    //@ts-ignore
                    value={answer || ""}
                    onChange={async ({ target }) => {
                        updateAnswer(currentQuestion.id, target.value, 0);
                        inputHC(target.value);
                    }
                    }
                    sx={{
                        "&:focus-visible": {
                            borderColor: theme.palette.primary.main
                        }
                    }}
                />
            </Box>
        </Box>
    );
};
