import { getQuizData } from "@/api/quizRelase";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";
import { QuizDataContext } from "@contexts/QuizDataContext";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
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 { startTransition, useEffect, useLayoutEffect, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import useSWR from "swr";
import { ApologyPage } from "./ViewPublicationPage/ApologyPage";
import ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import { QuizViewContext, createQuizViewStore } from "@/stores/quizView";


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 [quizViewStore] = useState(createQuizViewStore);
    const [rootContainerWidth, setRootContainerWidth] = useState<number>(() => window.innerWidth);
    const rootContainerRef = useRef<HTMLDivElement>(null);
    const { data, error, isLoading } = useSWR(quizSettings ? null : ["quizData", quizId], params => getQuizData(params[1]), {
        revalidateOnFocus: false,
        revalidateOnReconnect: false,
        shouldRetryOnError: false,
        refreshInterval: 0,
    });

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

    useEffect(() => {
        const handleWindowResize = () => {
            startTransition(() => {
                if (rootContainerRef.current) setRootContainerWidth(rootContainerRef.current.clientWidth);
            });
        };
        window.addEventListener("resize", handleWindowResize);

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

    if (isLoading) return <LoadingSkeleton />;
    if (error) return <ApologyPage error={error} />;

    quizSettings ??= data;
    if (!quizSettings) throw new Error("Quiz data is null");

    return (
        <QuizViewContext.Provider value={quizViewStore}>
            <RootContainerWidthContext.Provider value={rootContainerWidth}>
                <QuizDataContext.Provider value={{ ...quizSettings, 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>
        </QuizViewContext.Provider>
    );
} 
