import { QuizDataContext } from "@contexts/QuizDataContext";
import { QuizSettings } from "@model/settingsData";
import { Box, CssBaseline, ThemeProvider } from "@mui/material";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment";
import { ruRU } from '@mui/x-date-pickers/locales';
import { handleComponentError } from "@utils/handleComponentError";
import lightTheme from "@utils/themes/light";
import moment from "moment";
import { SnackbarProvider } from 'notistack';
import { ErrorBoundary } from "react-error-boundary";
import { ApologyPage } from "./ViewPublicationPage/ApologyPage";
import ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
import { startTransition, useEffect, useLayoutEffect, useRef, useState } from "react";
import { getQuizData } from "@/api/quizRelase";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";


moment.locale("ru");
const localeText = ruRU.components.MuiLocalizationProvider.defaultProps.localeText;

type Props = {
    quizSettings?: QuizSettings | {};
    quizId: string;
    preview?: boolean;
};

export default function QuizAnswerer({ quizSettings = {}, quizId, preview = false }: Props) {
    const [rootContainerWidth, setRootContainerWidth] = useState<number>(() => window.innerWidth);
    const [quizData, setQuizData] = useState<QuizSettings | {}>(quizSettings);
    const rootContainerRef = useRef<HTMLDivElement>(null);

    useLayoutEffect(() => {
        if (rootContainerRef.current) setRootContainerWidth(rootContainerRef.current.clientWidth);
    }, []);

    useEffect(() => {
        if (Object.values(quizSettings).length === 0) {
            const data = (async()=>await getQuizData(quizId))()
            setQuizData(data)
        }
        const handleWindowResize = () => {
            startTransition(() => {
                if (rootContainerRef.current) setRootContainerWidth(rootContainerRef.current.clientWidth);
            });
        };
        window.addEventListener("resize", handleWindowResize);

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

    if (Object.values(quizData).length === 0) return <LoadingSkeleton />;
    return (
        <RootContainerWidthContext.Provider value={rootContainerWidth}>
            <QuizDataContext.Provider value={{ ...quizData, quizId, preview }}>
                <LocalizationProvider dateAdapter={AdapterMoment} adapterLocale="ru" localeText={localeText}>
                    <ThemeProvider theme={lightTheme}>
                        <SnackbarProvider
                            preventDuplicate={true}
                            style={{ backgroundColor: lightTheme.palette.brightPurple.main }}
                        >
                            <CssBaseline />
                            <Box
                                ref={rootContainerRef}
                                sx={{
                                    width: "100%",
                                    height: "100%",
                                }}
                            >
                                <ErrorBoundary
                                    FallbackComponent={ApologyPage}
                                    onError={handleComponentError}
                                >
                                    <ViewPublicationPage />
                                </ErrorBoundary>
                            </Box>
                        </SnackbarProvider>
                    </ThemeProvider>
                </LocalizationProvider>
            </QuizDataContext.Provider>
        </RootContainerWidthContext.Provider>
    );
} 
