import createCache, { EmotionCache } from "@emotion/cache";
import { useMaterialUIController } from "../../ui-kit/context";
import { useEffect, useMemo, useState } from "react";
import { useLocation } from "react-router-dom";
import stylisRTLPlugin from "stylis-plugin-rtl";
import { CacheProvider } from "@emotion/react";
import { CssBaseline, ThemeProvider } from "@mui/material";
import createTheme from "../../ui-kit/assets/theme";
import createDarkTheme from "../../ui-kit/assets/theme-dark";
import themeRtl from "../../ui-kit/assets/theme/theme-rtl";
import themeDarkRTL from "../../ui-kit/assets/theme-dark/theme-rtl";
import palettes from "../../ui-kit/assets/theme/base/palettes";

type PageWrapperLayoutProps = {
  children: React.ReactNode;
}

const PageWrapperLayout = ({ children }: PageWrapperLayoutProps): JSX.Element => {

  const [controller] = useMaterialUIController();
  const {
    direction,
    darkMode,
    themeColor,
  } = controller;
  const [rtlCache, setRtlCache] = useState<EmotionCache | null>(null);
  const { pathname } = useLocation();

  // Cache for the rtl
  useMemo(() => {
    const cacheRtl = createCache({
      key: "rtl",
      stylisPlugins: [stylisRTLPlugin],
    });

    setRtlCache(cacheRtl);
  }, []);

  // Setting the dir attribute for the body element
  useEffect(() => {
    document.body.setAttribute("dir", direction);
  }, [direction]);

  // Setting page scroll to 0 when changing the route
  useEffect(() => {
    document.documentElement.scrollTop = 0;
    if (document.scrollingElement) {
      document.scrollingElement.scrollTop = 0;
    }
  }, [pathname]);

  return direction === "rtl" ? (
    <CacheProvider value={rtlCache}>
      <ThemeProvider theme={darkMode ? themeDarkRTL : themeRtl}>
        <CssBaseline />
        {children}


      </ThemeProvider>
    </CacheProvider>
  ) : (
    <ThemeProvider theme={darkMode ? createDarkTheme((palettes as any)[themeColor] || (palettes as any).blue) : createTheme((palettes as any)[themeColor] || (palettes as any).blue)}>
      <CssBaseline />
      {children}

    </ThemeProvider>
  );


}

export default PageWrapperLayout;
