import { useLayoutEffect, 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 type { AnyTypedQuizQuestion } from "../../model/questionTypes/shared";

export const ViewPage = () => {
  const [stepNumber, setStepNumber] = useState<number>(0);
  const quiz = useCurrentQuiz();
  const { questions } = useQuestions();

  useLayoutEffect(() => {
    if (stepNumber === 0 && quiz?.config.noStartPage) {
      setStepNumber(1);
    }
  }, []);

  const filteredQuestions = questions.filter(
    ({ type }) => type
  ) as AnyTypedQuizQuestion[];

  return (
    <Box>
      {stepNumber ? (
        <Question
          stepNumber={stepNumber}
          setStepNumber={setStepNumber}
          questions={filteredQuestions}
        />
      ) : (
        <StartPageViewPublication
          setStepNumber={setStepNumber}
          showNextButton={!!filteredQuestions.length}
        />
      )}
    </Box>
  );
};
