import { Button, ThemeProvider, useTheme } from "@mui/material";
import { useQuizViewStore } from "@stores/quizView";
import { useQuestionFlowControl } from "@utils/hooks/useQuestionFlowControl";
import { useQuizData } from "@contexts/QuizDataContext";
import { notReachable } from "@utils/notReachable";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { ReactElement, useEffect } from "react";
import { useRootContainerSize } from "../../contexts/RootContainerWidthContext";
import { ContactForm } from "./ContactForm";
import { Question } from "./Question";
import { ResultForm } from "./ResultForm";
import { StartPageViewPublication } from "./StartPageViewPublication";
import PrevButton from "./tools/PrevButton";
import NextButton from "./tools/NextButton";
import { enqueueSnackbar } from "notistack";
import { sendAnswer } from "@api/quizRelase";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";

export default function ViewPublicationPage() {
  const { settings, recentlyCompleted, quizId } = useQuizData();
  const { answers } = useQuizViewStore();
  let currentQuizStep = useQuizViewStore((state) => state.currentQuizStep);
  const isMobileMini = useRootContainerSize() < 382;
  const {
    currentQuestion,
    currentQuestionStepNumber,
    isNextButtonEnabled,
    isPreviousButtonEnabled,
    moveToPrevQuestion,
    moveToNextQuestion,
    showResultAfterContactForm,
  } = useQuestionFlowControl();

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

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

        document.title = settings.name;
      }

    },
    [settings]
  );

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

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

      quizStepElement = (
        <Question
          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,
                    });
                  } catch (e) {
                    enqueueSnackbar("ответ не был засчитан");
                  }
                }
                moveToNextQuestion()
              }}
            />}
        />
      );
      break;
    }
    case "contactform": {
      quizStepElement = (
        <ContactForm
          currentQuestion={currentQuestion}
          onShowResult={showResultAfterContactForm}
        />
      );
      break;
    }
    default:
      notReachable(currentQuizStep);
  }

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