import { useQuizData } from "@/api/hooks";
import { QuizViewContext, createQuizViewStore } from "@/stores/quizView";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import { QuizSettingsContext } from "@contexts/QuizDataContext";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
import type { QuizSettings } from "@model/settingsData";
import { Box, CssBaseline, ScopedCssBaseline, 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 { ApologyPage } from "./ViewPublicationPage/ApologyPage";
import ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import { HelmetProvider } from "react-helmet-async";

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 } = useQuizData(quizId, preview);
  const vkMetrics = useVkMetricsGoals(quizSettings?.settings.cfg.vkMetricsNumber);
  const yandexMetrics = useYandexMetricsGoals(quizSettings?.settings.cfg.yandexMetricsNumber);

  useEffect(() => {
    setTimeout(() => {
      vkMetrics.quizOpened();
      yandexMetrics.quizOpened();
    }, 4000);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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} />;
  // if (!data) return <LoadingSkeleton />;
  quizSettings ??= data;
  if (!quizSettings) return <ApologyPage error={new Error("Quiz data is null")} />;

  if (quizSettings.questions.length === 1 && quizSettings?.settings.cfg.noStartPage)
    return <ApologyPage error={new Error("Quiz is empty")} />;
  // if (quizSettings.questions.length === 1) 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}>
        <QuizSettingsContext.Provider value={{ ...quizSettings, quizId, preview, changeFaviconAndTitle }}>
          {disableGlobalCss ? (
            <ScopedCssBaseline
              sx={{
                height: "100%",
                width: "100%",
                backgroundColor: "transparent",
              }}
            >
              {quizContainer}
            </ScopedCssBaseline>
          ) : (
            <CssBaseline>{quizContainer}</CssBaseline>
          )}
        </QuizSettingsContext.Provider>
      </RootContainerWidthContext.Provider>
    </QuizViewContext.Provider>
  );
}

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