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

import CustomTextField from "@ui_kit/CustomTextField";

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

import type { QuizQuestionText } from "../../../model/questionTypes/text";
import { enqueueSnackbar } from "notistack";
import { useQuestionsStore } from "@stores/quizData/store"
import { sendAnswer } from "@api/quizRelase";
import { useDebouncedCallback } from "use-debounce";

type TextProps = {
  currentQuestion: QuizQuestionText;
};

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

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

      await sendAnswer({
        questionId: currentQuestion.id,
        body: text,
        //@ts-ignore
        qid: settings.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)
            inputHC(target.value)
          }
          }
          sx={{
            "&:focus-visible": {
              borderColor: theme.palette.primary.main
            }
          }}
        />
      </Box>
    </Box>
  );
};
