'use client';

import { AppLoader } from '@/components/AppLoader';
import { useAppStore } from '@/store/app.store';
import { useAuthStore } from '@/store/auth.store';
import { getRoutePermission } from '@/config/app.routes';
import { usePermissions } from '@/hooks/usePermissions';
import { ROUTES } from '@/utils/routes';
import { usePathname, useRouter } from 'next/navigation';
import type { ReactNode } from 'react';
import { useEffect } from 'react';

export function AuthGuard({ children }: { children: ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const accessToken = useAuthStore((state) => state.accessToken);
  const isInitialized = useAppStore((state) => state.isInitialized);
  const user = useAppStore((state) => state.user);
  const { hasPermission } = usePermissions();
  const requiredPermission = getRoutePermission(pathname);
  const canAccessRoute = hasPermission(requiredPermission);

  useEffect(() => {
    if (!isInitialized) return;

    if (!accessToken) {
      router.replace(ROUTES.LOGIN);
    }
  }, [accessToken, isInitialized, router]);

  useEffect(() => {
    if (!isInitialized || !accessToken || !user || canAccessRoute) return;

    router.replace(ROUTES.ACCESS);
  }, [accessToken, canAccessRoute, isInitialized, router, user]);

  if (!isInitialized || (accessToken && !user)) {
    return <AppLoader label="Preparing workspace" />;
  }

  if (!accessToken || !user || !canAccessRoute) {
    return null;
  }

  return children;
}
