import { getData } from "@api/quizRelase";
import { QuizSettings } from "@model/settingsData";
import { Box, ThemeProvider } from "@mui/material";
import { setQuizData } from "@stores/quizData/actions";
import { useQuestionsStore } from "@stores/quizData/store";
import LoadingSkeleton from "@ui_kit/LoadingSkeleton";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { enqueueSnackbar } from "notistack";
import { useEffect, useState } from "react";
import useSWR from "swr";
import { ApologyPage } from "./ApologyPage";
import { Question } from "./Question";
import { StartPageViewPublication } from "./StartPageViewPublication";

import { parseQuizData } from "@model/api/getQuizData";
import { replaceSpacesToEmptyLines } from "./tools/replaceSpacesToEmptyLines";
import { useQuizId } from "../../contexts/QuizIdContext";


export const ViewPage = () => {
    const quizId = useQuizId();
    const { isLoading, error } = useSWR(["quizData", quizId], params => getQuizData(params[1]), {
        onSuccess: setQuizData,
    });
    const { settings, items, recentlyСompleted } = useQuestionsStore();
    const [visualStartPage, setVisualStartPage] = useState<boolean>();

    useEffect(() => {//установка фавиконки
        if (!settings) return;

        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 = items.filter(({ type }) => type !== null && type !== "result").length;

    if (error) {
        console.log(error);
        return <ApologyPage message="Что-то пошло не так" />;
    }
    if (isLoading || !settings) return <LoadingSkeleton />;
    if (questionsCount === 0) return <ApologyPage message="Нет созданных вопросов" />;

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

async function getQuizData(quizId: string) {
    const response = await getData(quizId);
    const quizDataResponse = response.data;

    if (response.error) {
        enqueueSnackbar(response.error);
        throw new Error(response.error);
    }
    if (!quizDataResponse) {
        throw new Error("Quiz not found");
    }

    const quizSettings = replaceSpacesToEmptyLines(parseQuizData(quizDataResponse, quizId));

    return JSON.parse(JSON.stringify({ data: quizSettings }).replaceAll(/\\" \\"/g, '""').replaceAll(/" "/g, '""')).data as QuizSettings & { recentlyСompleted: boolean; };
}
