import {sendAnswer} from "@api/quizRelase";
import {useQuizData} from "@contexts/QuizDataContext";
import {ThemeProvider, Typography} from "@mui/material";
import {useQuizViewStore} from "@stores/quizView";
import {useQuestionFlowControl} from "@utils/hooks/useQuestionFlowControl";
import {notReachable} from "@utils/notReachable";
import {quizThemes} from "@utils/themes/Publication/themePublication";
import {enqueueSnackbar} from "notistack";
import {ReactElement, useEffect} from "react";
import {Question} from "./Question";
import {ResultForm} from "./ResultForm";
import {StartPageViewPublication} from "./StartPageViewPublication";
import NextButton from "./tools/NextButton";
import PrevButton from "./tools/PrevButton";
import QuestionSelect from "./QuestionSelect";
import {useYandexMetrics} from "@/utils/hooks/useYandexMetrics";
import {useVKMetrics} from "@/utils/hooks/useVKMetrics";
import {
  ContactForm
} from "@/components/ViewPublicationPage/ContactForm/ContactForm.tsx";

export default function ViewPublicationPage() {
  const {
    settings,
    recentlyCompleted,
    quizId,
    preview,
    changeFaviconAndTitle,
  } = useQuizData();
  const answers = useQuizViewStore((state) => state.answers);
  let currentQuizStep = useQuizViewStore((state) => state.currentQuizStep);
  const {
    currentQuestion,
    currentQuestionStepNumber,
    isNextButtonEnabled,
    isPreviousButtonEnabled,
    moveToPrevQuestion,
    moveToNextQuestion,
    showResultAfterContactForm,
    setQuestion,
  } = useQuestionFlowControl();
  useYandexMetrics(settings?.cfg?.yandexMetricNumber);
  useVKMetrics(settings?.cfg?.vkMetricNumber);

  const isAnswer = answers.some(
    (ans) => ans.questionId === currentQuestion?.id
  );

  useEffect(
    function setFaviconAndTitle() {
      if (!changeFaviconAndTitle) return;

      const link = document.querySelector('link[rel="icon"]');
      if (link && settings.cfg.startpage.favIcon) {
        link.setAttribute("href", settings.cfg.startpage.favIcon);
      }

      document.title = settings.name;
    },
    [changeFaviconAndTitle, settings.cfg.startpage.favIcon, settings.name]
  );

  if (recentlyCompleted) throw new Error("Quiz already completed");
  if (currentQuizStep === "startpage" && settings.cfg.noStartPage)
    currentQuizStep = "question";

  if (!currentQuestion)
    return (
      <ThemeProvider
        theme={quizThemes[settings.cfg.theme || "StandardTheme"].theme}
      >
        <Typography textAlign={"center"} mt="50px">
          Вопрос не выбран
        </Typography>
      </ThemeProvider>
    );


  let quizStepElement: ReactElement;
  switch (currentQuizStep) {
    case "startpage": {
      quizStepElement = <StartPageViewPublication />;
      break;
    }
    case "question": {
      if (currentQuestion.type === "result") {
        quizStepElement = <ResultForm resultQuestion={currentQuestion} />;
        break;
      }

      quizStepElement = (
        <Question
          key={currentQuestion.id}
          currentQuestion={currentQuestion}
          currentQuestionStepNumber={currentQuestionStepNumber}
          prevButton={
            <PrevButton
              isPreviousButtonEnabled={isPreviousButtonEnabled}
              moveToPrevQuestion={moveToPrevQuestion}
            />
          }
          nextButton={
            <NextButton
              isNextButtonEnabled={isNextButtonEnabled}
              moveToNextQuestion={async () => {
                if (!isAnswer) {
                  try {
                    await sendAnswer({
                      questionId: currentQuestion.id,
                      body: "",
                      qid: quizId,
                      preview,
                    });
                  } catch (e) {
                    enqueueSnackbar("ответ не был засчитан");
                  }
                }
                moveToNextQuestion();
              }}
            />
          }
          questionSelect={
            <QuestionSelect
              selectedQuestion={currentQuestion}
              setQuestion={setQuestion}
            />
          }
        />
      );
      break;
    }
    case "contactform": {
      quizStepElement = (
        <ContactForm
          currentQuestion={currentQuestion}
          onShowResult={showResultAfterContactForm}
        />
      );
      break;
    }
    default:
      notReachable(currentQuizStep);
  }

  return (
    <ThemeProvider
      theme={quizThemes[settings.cfg.theme || "StandardTheme"].theme}
    >
      {quizStepElement}
    </ThemeProvider>
  );
}
