import { getQuizData } from "@api/quizRelase";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
import { Box } from "@mui/material";
import LoadingSkeleton from "@ui_kit/LoadingSkeleton";
import { startTransition, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import useSWR from "swr";
import QuizAnswerer from "../lib/components/QuizAnswerer";
import { ApologyPage } from "../lib/components/ViewPublicationPage/ApologyPage";

//const defaultQuizId = "0c568ac9-d176-491b-b6cd-5afd31254951"; // branching
const defaultQuizId = "d7c940fe-1e44-41a0-bbac-5f304c51a1e4"; //looooong header
// const defaultQuizId = "ad7f5a87-b833-4f5b-854e-453706ed655c"; // linear

export default function App() {
    const quizId = useParams().quizId ?? defaultQuizId;
    const [rootContainerSize, setRootContainerSize] = useState<number>(() => window.innerWidth);
    const { data, error, isLoading } = useSWR(["quizData", quizId], params => getQuizData(params[1]), {
        revalidateOnFocus: false,
        revalidateOnReconnect: false,
        shouldRetryOnError: false,
        refreshInterval: 0,
    });

    useEffect(() => {
        const handleWindowResize = () => {
            startTransition(() => {
                setRootContainerSize(window.innerWidth);
            });
        };
        window.addEventListener("resize", handleWindowResize);

        return () => {
            window.removeEventListener("resize", handleWindowResize);
        };
    }, []);

    if (isLoading) return <LoadingSkeleton />;
    if (error) return <ApologyPage error={error} />;
    if (!data) throw new Error("Quiz data is null");

    return (
        <RootContainerWidthContext.Provider value={rootContainerSize}>
            <Box sx={{
                height: "100dvh",
            }}>
                <QuizAnswerer quizSettings={data} quizId={quizId} />
            </Box>
        </RootContainerWidthContext.Provider>
    );
}
