import { Suspense } from "react";
import { Routes, Route } from "react-router-dom";
import { RoutesDef, hasApprovalPermission } from "./routes";
import { useUserDetail } from "../components/hooks/useUserDetail";
import { useMemo } from "react";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import Loader from "../components/Loader/loader";
import { ErrorBoundary } from "../components/common/ErrorBoundary";

const RouteLoader = () => (
  <div className="flex items-center justify-center h-64">
    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
  </div>
);

const RouterContainer = () => {
  const { userDetails, selectedPositionPermissionKeys } = useAuthUser();
  const { permissionKeys, isLoading, error } = useUserDetail(userDetails);

  const effectivePermissionKeys = useMemo(() => {
    if (
      hasApprovalPermission(permissionKeys || []) &&
      !hasApprovalPermission(selectedPositionPermissionKeys)
    ) {
      return (permissionKeys || []).filter(
        (permission) => !["can:sendToRO", "can:approveRecords"].includes(permission),
      );
    }

    return permissionKeys || [];
  }, [permissionKeys, selectedPositionPermissionKeys]);

  // Memoize routes to prevent recreation on every render
  const routes = useMemo(() => {
    return RoutesDef(effectivePermissionKeys, selectedPositionPermissionKeys);
  }, [effectivePermissionKeys, selectedPositionPermissionKeys]);

  if (isLoading) {
    return (
      <Loader className="min-h-screen" label="Loading Record Management..." />
    );
  }
  if (error) return <div>Error loading permissions</div>;

  return (
    <ErrorBoundary>
    <Suspense fallback={<RouteLoader />}>
      <Routes>
        {routes.map((route, index) => {
          const routeProps: any = { element: route.element };
          if (route.index) {
            routeProps.index = true;
          } else {
            routeProps.path = route.path;
          }
          return (
            <Route {...routeProps} key={index}>
              {route?.children?.map((child, index2) => {
                const childProps: any = { element: child.element };
                if (child.index) {
                  childProps.index = true;
                } else {
                  childProps.path = child.path;
                }
                return <Route {...childProps} key={index2} />;
              })}
            </Route>
          );
        })}
      </Routes>
    </Suspense>
    </ErrorBoundary>
  );
};

export default RouterContainer;
