'use client';

import { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';
import { Loader2 } from 'lucide-react';
import { canAccessAdmin } from '@/lib/auth/authorization';

interface AdminRouteGuardProps {
  children: React.ReactNode;
}

/**
 * Admin Route Guard Component
 *
 * Protects admin routes by checking if the user is authenticated
 * and has admin privileges (is_superuser or has 'admin' permission).
 */
export function AdminRouteGuard({ children }: AdminRouteGuardProps) {
  const router = useRouter();
  const pathname = usePathname();
  const { status, isLoading, hasHydrated, user } = useAuthStore();

  useEffect(() => {
    // Only redirect after hydration is complete
    if (hasHydrated && !isLoading) {
      if (status === 'anonymous') {
        // Redirect to login with return URL
        const loginUrl = `/login?redirect=${encodeURIComponent(pathname)}`;
        router.push(loginUrl);
      } else if (status === 'authenticated' && !canAccessAdmin(user)) {
        // User is authenticated but not an admin - redirect to home
        router.push('/');
      }
    }
  }, [status, isLoading, hasHydrated, router, pathname, user]);

  // Show loading state while hydrating or checking authentication
  if (!hasHydrated || isLoading || status === 'idle') {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // Only render children if authenticated and admin
  if (status !== 'authenticated') {
    return null;
  }

  // Check admin permission
  const isAdmin = canAccessAdmin(user);
  if (!isAdmin) {
    return null;
  }

  return <>{children}</>;
}

export default AdminRouteGuard;
