import { startTransition, useEffect, useLayoutEffect, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import useSWR from "swr";
import { SnackbarProvider } from "notistack";
import moment from "moment";
import { Box, ScopedCssBaseline, 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 ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import { ApologyPage } from "./ViewPublicationPage/ApologyPage";

import { QuizViewContext, createQuizViewStore } from "@/stores/quizView";

import { getQuizData } from "@/api/quizRelase";

import { QuizDataContext } from "@contexts/QuizDataContext";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";

import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import { handleComponentError } from "@utils/handleComponentError";
import lightTheme from "@utils/themes/light";

import type { QuizSettings } from "@model/settingsData";

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

type Props = {
  quizSettings?: QuizSettings;
  quizId: string;
  preview?: boolean;
  changeFaviconAndTitle?: boolean;
  className?: string;
  disableGlobalCss?: boolean;
};

function QuizAnswererInner({
  quizSettings,
  quizId,
  preview = false,
  changeFaviconAndTitle = true,
  className,
  disableGlobalCss = 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,
    }
  );
  const vkMetrics = useVkMetricsGoals(quizSettings?.settings.cfg.vkMetricsNumber);
  const yandexMetrics = useYandexMetricsGoals(quizSettings?.settings.cfg.yandexMetricsNumber);

  useEffect(() => {
    setTimeout(() => {
      vkMetrics.quizOpened();
      yandexMetrics.quizOpened();
    }, 4000);
  }, []);

  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");

  if (quizSettings.questions.length === 0) return <ApologyPage error={new Error("No questions found")} />;
  if (!quizId) return <ApologyPage error={new Error("No quiz id")} />;

  const quizContainer = (
    <Box
      ref={rootContainerRef}
      className={className}
      sx={{
        width: "100%",
        height: "100%",
        position: "relative",
      }}
    >
      <ErrorBoundary FallbackComponent={ApologyPage} onError={handleComponentError}>
        <ViewPublicationPage />
      </ErrorBoundary>
    </Box>
  );

  return (
    <QuizViewContext.Provider value={quizViewStore}>
      <RootContainerWidthContext.Provider value={rootContainerWidth}>
        <QuizDataContext.Provider value={{ ...quizSettings, quizId, preview, changeFaviconAndTitle }}>
          {disableGlobalCss ? (
            <ScopedCssBaseline
              sx={{
                height: "100%",
                width: "100%",
                backgroundColor: "transparent",
              }}
            >
              {quizContainer}
            </ScopedCssBaseline>
          ) : (
            <CssBaseline>{quizContainer}</CssBaseline>
          )}
        </QuizDataContext.Provider>
      </RootContainerWidthContext.Provider>
    </QuizViewContext.Provider>
  );
}

export default function QuizAnswerer(props: Props) {
  return (
    <LocalizationProvider dateAdapter={AdapterMoment} adapterLocale="ru" localeText={localeText}>
      <ThemeProvider theme={lightTheme}>
        <SnackbarProvider preventDuplicate={true} style={{ backgroundColor: lightTheme.palette.brightPurple.main }}>
          <QuizAnswererInner {...props} />
        </SnackbarProvider>
      </ThemeProvider>
    </LocalizationProvider>
  );
}
