"use client";

import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { useEffect, ReactNode } from "react";

interface RoleGuardProps {
  children: ReactNode;
  allowedRoles: string[];
  fallbackPath?: string;
}

export default function RoleGuard({
  children,
  allowedRoles,
  fallbackPath = "/dashboard",
}: RoleGuardProps) {
  const { user, isLoading, hasRole } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading) {
      if (!user) {
        // User not authenticated
        router.push("/login");
        return;
      }

      // Check if user has any of the required roles
      const hasRequiredRole = allowedRoles.some((role) => hasRole(role));

      if (!hasRequiredRole) {
        // User doesn't have required role, redirect to fallback
        router.push(fallbackPath);
        return;
      }
    }
  }, [user, isLoading, allowedRoles, router, fallbackPath, hasRole]);

  // Show loading or nothing while checking authentication/authorization
  if (isLoading || !user) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  // Check if user has required role
  const hasRequiredRole = allowedRoles.some((role) => hasRole(role));

  if (!hasRequiredRole) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-2">
            Access Denied
          </h2>
          <p className="text-gray-600">
            You don't have permission to access this page.
          </p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
