import { questionApi } from "@api/question";
import { devlog } from "@frontend/kitui";
import { QuizAnswerer } from "@frontend/squzanswerer";
import { rawQuestionToQuestion } from "@model/question/question";
import { Box } from "@mui/material";
import { useQuizes } from "@root/quizes/hooks";
import { isAxiosError } from "axios";
import { enqueueSnackbar } from "notistack";
import { useParams } from "react-router-dom";
import useSWR from "swr";
import { useYandexMetrics } from "@utils/hooks/useYandexMetrics";

export default function ViewPublicationPage() {
  const quizId = useParams().quizId;
  const {
    quizes,
    error: quizesError,
    isLoading: quizesIsLoading,
  } = useQuizes();

  if (!quizId) return null;

  const quiz = quizes?.find((quiz) => quiz.qid === quizId);
  const yandexMetricsNumber = quiz?.config.yandexMetricsNumber;

  useYandexMetrics(yandexMetricsNumber);

  const {
    data: rawQuestions,
    isLoading: questionsIsLoading,
    error: questionsError,
  } = useSWR(
    ["questions", quiz?.backendId],
    ([, id]) => questionApi.getList({ quiz_id: id }),
    {
      onError: (error) => {
        const message = isAxiosError<string>(error)
          ? error.response?.data ?? ""
          : "";

        devlog("Error getting question list", error);
        enqueueSnackbar(`Не удалось получить вопросы. ${message}`);
      },
    },
  );

  if (quizesError) {
    console.error(`Error fetching quiz ${quizId}`, quizesError);
    return null;
  }
  if (questionsError) {
    console.error(`Error fetching questions ${quizId}`, questionsError);
    return null;
  }

  if (quizesIsLoading) return null;
  if (questionsIsLoading) return null;

  if (!quiz) throw new Error("Quiz not found");
  if (!rawQuestions?.[0]) throw new Error("Questions not found");

  const questions = rawQuestions[0].map(rawQuestionToQuestion);
  return (
    <Box
      sx={{
        height: "100dvh",
      }}
    >
      <QuizAnswerer
        quizSettings={{
          cnt: rawQuestions[0]?.length,
          questions,
          recentlyCompleted: false,
          settings: {
            fp: quiz.fingerprinting,
            delay: 0,
            due: quiz.due_to,
            lim: quiz.limit,
            name: quiz.name,
            pausable: quiz.pausable,
            rep: quiz.repeatable,
            cfg: quiz.config,
          },
          show_badge: true,
        }}
        quizId={quizId}
        preview
      />
    </Box>
  );
}
