import { useEffect, useState } from "react";
import { Box } from "@mui/material";

import { StartPageViewPublication } from "./StartPageViewPublication";
import { Question } from "./Question";
import { useQuestions } from "@root/questions/hooks";
import { useCurrentQuiz } from "@root/quizes/hooks";
import useSWR from "swr";
import { quizApi } from "@api/quiz";
import { setQuizes } from "@root/quizes/actions";
import { isAxiosError } from "axios";
import { devlog } from "@frontend/kitui";
import { useQuizStore } from "@root/quizes/store";

import type { AnyTypedQuizQuestion } from "../../model/questionTypes/shared";
import { enqueueSnackbar } from "notistack";
import { useQuestionsStore } from "@root/questions/store";
import { setQuestions } from "@root/questions/actions";
import { questionApi } from "@api/question";

export const ViewPage = () => {
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();
  const { questions } = useQuestionsStore();

  useEffect(() => {
    const getData = async () => {
      const quizes = await quizApi.getList();
      setQuizes(quizes);

      if (!editQuizId) {
        return;
      }

      const questions = await questionApi.getList({ quiz_id: editQuizId });
      setQuestions(questions);
    };
    getData();
  }, []);
  useEffect(() => {
    setVisualStartPage(quiz?.config.noStartPage);
  }, [questions]);

  const [visualStartPage, setVisualStartPage] = useState<boolean>();

  useEffect(() => {
    const link = document.querySelector('link[rel="icon"]');

    if (link && quiz?.config.startpage.favIcon) {
      link.setAttribute("href", quiz.config.startpage.favIcon);
    }
  }, [quiz?.config.startpage.favIcon]);

  const filteredQuestions = (
    questions.filter(({ type }) => type) as AnyTypedQuizQuestion[]
  ).sort((previousItem, item) => previousItem.page - item.page);

  console.log("visualStartPage ", visualStartPage);
  if (visualStartPage === undefined) return <></>;
  return (
    <Box>
      {!visualStartPage ? (
        <StartPageViewPublication setVisualStartPage={setVisualStartPage} />
      ) : (
        <Question questions={filteredQuestions} />
      )}
    </Box>
  );
};
