import type { ReactNode } from 'react';
import { Suspense } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useShellOutletContext } from '@/app/shellOutletContext';
import { StatePanel } from '@/components/ui/state-panel';
import {
  canUserRoleAccessModuleRoute,
  DEFAULT_MODULE_ROUTE_PATH,
} from '@/shared/constants/moduleRoutes';

interface ModuleRouteGuardProps {
  readonly children: ReactNode;
}

export function ModuleRouteGuard({ children }: ModuleRouteGuardProps) {
  const location = useLocation();
  const shell = useShellOutletContext();

  if (!canUserRoleAccessModuleRoute(location.pathname, shell.userRole)) {
    return <Navigate to={DEFAULT_MODULE_ROUTE_PATH} replace />;
  }

  return (
    <Suspense
      fallback={(
        <StatePanel tone="violet" alignment="center" loading className="my-20">
          Loading module...
        </StatePanel>
      )}
    >
      {children}
    </Suspense>
  );
}
