import React, { Suspense, lazy, useEffect } from "react";
import { Route, Routes, useNavigate } from "react-router-dom";
import Layout from "./Layout/Ui/Layout";
import { CrudRoute, menuItems } from "./Routes";
import { Spin } from "antd";
import { hasAbility } from "./utils/hasAbility";
import { useChangeLanguage } from "./Hooks/useChangeLanguage";
import useAuthState from "./zustand/AuthState";
import { TMenuItem } from "./types/App";
import { useTranslation } from "react-i18next";
import SpinContainer from "./Components/Layout/SpinContainer";

const Page404 = lazy(() => import("./Layout/Ui/NotFoundPage"));
const Auth = lazy(() => import("./Pages/Auth/Page"));

const App = () => {
  const { changeLanguage } = useChangeLanguage();
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthState();
  const [t] = useTranslation()

  useEffect(() => {
    if (!isAuthenticated) {
      navigate("/auth");
    }
  }, [isAuthenticated, navigate]);

  const renderRouteElement = (route: any) => (
    <Suspense fallback={<Layout> <SpinContainer/> </Layout>}>
      {route.header ? (
        <Layout>{route.element}</Layout>
      ) : (
        route.element || <h1>please Create the Page</h1>
      )}
    </Suspense>
  );

  const renderRoutesRecursively = (routes:TMenuItem[]) =>
    routes.map((route: TMenuItem) => {
      const useAbility = hasAbility(route.abilities, route.abilities_value);
      const tableHeader = t(`${route?.header}`);
      // useSetPage_title(tableHeader,route?.path);
    
      if (useAbility) {
        return (
          <React.Fragment key={route.path}>
            <Route path={route.path} element={renderRouteElement(route)} />
            {route.children && renderRoutesRecursively(route.children)}
          </React.Fragment>
        );
      }
      return null;
    });

  return (
    <Routes>
      <Route
        key={"auth"}
        path={"/auth"}
        element={
          <Suspense fallback={<Spin />}>
            {" "}
            <Auth />{" "}
          </Suspense>
        }
      />
      <Route
        key={"Page404"}
        path={"/*"}
        element={
          <Suspense fallback={<Spin />}>
            {" "}
            <Page404 />{" "}
          </Suspense>
        }
      />

      {renderRoutesRecursively(menuItems)}

      {CrudRoute.map((route) => {
        const useAbility = hasAbility(route.abilities, route.abilities_value);
        const tableHeader = t(`${route?.header}`);
        // useSetPage_title(tableHeader,route?.path);
        
        if (!useAbility) {
          return false;
        }
        return (
          <Route
            key={route.path ?? ""}
            path={route.path ?? ""}
            element={renderRouteElement(route)}
          />
        );
      })}
    </Routes>
  );
};

export default App;
