/* eslint-disable react-hooks/exhaustive-deps */
"use client";

import { usePathname } from "next/navigation";
import HomeLayout from "@/components/HomeLayout/HomeLayout";
import { ReactNode, useEffect } from "react";
import { ThemeProvider } from "@mui/material";
import theme from "@/styles/muiTheme";
import BackendFetching from "@/lib/services/context/class";
import FetchingContext from "@/lib/services/context/fetchingContext";
import GlobalNotifications from "../GlobalNotifications/GlobalNotifications";
import useRequestHandler from "@/hooks/useRequestHandler/useRequestHandler";
import { recoveryTokenResponse } from "@/lib/services/redux/reducers/user/userActions.d";
import { recoveryTokenParams } from "@/lib/services/redux/reducers/user/userActions.d";
import { recoveryToken } from "@/lib/services/redux/reducers/user/userActions";
import { CircularProgress } from "@mui/material";
import styles from "./styles.module.scss";
type Pathnames = "auth" | "home" | "admin" | "super-admin";

function getLayout(children: ReactNode, path: Pathnames) {
  switch (path) {
    case "home":
      return <HomeLayout>{children}</HomeLayout>;
    default:
      return <HomeLayout>{children}</HomeLayout>;
  }
}

const MainLayoutRenderer = ({ children }: { children: ReactNode }) => {
  const pathname = usePathname();
  const pathInit = pathname.split("/");
  const path = (pathInit.length > 1 ? pathInit[1] : "home") as Pathnames;

  const { fetcher: recoveryTokenFetch, requestStatus: recoveryTokenStatus } =
    useRequestHandler<recoveryTokenResponse, recoveryTokenParams>(
      recoveryToken
    );

  useEffect(() => {
    recoveryTokenFetch(null);
  }, []);

  if (recoveryTokenStatus.loading) {
    return (
      <div className={styles.pageContainer}>
        <CircularProgress size={50} color="primary" />
      </div>
    );
  }
  return (
    <ThemeProvider theme={theme}>
      <>{getLayout(children, path)}</>
      <GlobalNotifications />
    </ThemeProvider>
  );
};

export default function LayoutController({
  children,
}: {
  children: ReactNode;
}) {
  const backendInstance = new BackendFetching();

  return (
    <FetchingContext.Provider value={backendInstance}>
      <MainLayoutRenderer>{children}</MainLayoutRenderer>
    </FetchingContext.Provider>
  );
}
