import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { enqueueSnackbar } from "notistack";

import { TextSpecial } from "./TextSpecial";
import { TextNormal } from "./TextNormal";

import { sendAnswer } from "@api/quizRelase";
import { useQuizViewStore } from "@stores/quizView";
import { useQuizSettings } from "@contexts/QuizDataContext";

import type { QuizQuestionText } from "@model/questionTypes/text";

type TextProps = {
  currentQuestion: QuizQuestionText;
  stepNumber: number | null;
};

export const Text = ({ currentQuestion, stepNumber }: TextProps) => {
  const [isSending, setIsSending] = useState<boolean>(false);
  const { settings, preview, quizId } = useQuizSettings();
  const answers = useQuizViewStore((state) => state.answers);
  const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};

  const inputHC = useDebouncedCallback(async (text) => {
    setIsSending(true);

    try {
      await sendAnswer({
        questionId: currentQuestion.id,
        body: text,
        qid: quizId,
        preview,
      });
    } catch (error) {
      enqueueSnackbar("ответ не был засчитан");
    }

    setIsSending(false);
  }, 400);

  useEffect(() => {
    inputHC.flush();
  }, [inputHC]);

  switch (settings.cfg.spec) {
    case true:
      return (
        <TextSpecial currentQuestion={currentQuestion} answer={answer} inputHC={inputHC} stepNumber={stepNumber} />
      );

    case undefined:
      return <TextNormal currentQuestion={currentQuestion} answer={answer} inputHC={inputHC} />;

    default:
      return <TextNormal currentQuestion={currentQuestion} answer={answer} inputHC={inputHC} />;
  }
};
