import { Box, ThemeProvider } from "@mui/material";
import { useQuizData } from "@utils/hooks/useQuizData";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { useEffect, useState } from "react";
import { ApologyPage } from "./ApologyPage";
import { Question } from "./Question";
import { StartPageViewPublication } from "./StartPageViewPublication";


export const ViewPage = () => {
    const { settings, questions, recentlyCompleted } = useQuizData();
    const [visualStartPage, setVisualStartPage] = useState<boolean>();

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

        document.title = settings.name;

        setVisualStartPage(!settings.cfg.noStartPage);
    }, [settings]);

    const questionsCount = questions.filter(({ type }) => type !== null && type !== "result").length;
    if (questionsCount === 0) return <ApologyPage message="Нет созданных вопросов" />;

    return (
        <ThemeProvider theme={quizThemes[settings.cfg.theme || "StandardTheme"]}>
            {recentlyCompleted ? (
                <ApologyPage message="Вы уже прошли этот опрос" />
            ) : (
                <Box>
                    {visualStartPage ? (
                        <StartPageViewPublication setVisualStartPage={setVisualStartPage} />
                    ) : (
                        <Question />
                    )}
                </Box>
            )}
        </ThemeProvider>
    );
}; 
