import { ReactNode } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/contexts/AuthContext";
import { UserRole } from "@/types/auth";

interface ProtectedRouteProps {
  children: ReactNode;
  requiredRoles: UserRole[];
  fallbackRoute?: string;
  showFallback?: boolean;
}

const ProtectedRoute = ({
  children,
  requiredRoles,
  fallbackRoute = "/dashboard",
  showFallback = true,
}: ProtectedRouteProps) => {
  const { loading, isAuthenticated, canAccess } = useAuth();
  const router = useRouter();

  // Mostrar loading enquanto verifica autenticação
  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-green-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Verificando permissões...</p>
        </div>
      </div>
    );
  }

  // Redirecionar se não autenticado
  if (!isAuthenticated) {
    router.push("/");
    return null;
  }

  // Verificar se tem permissão
  if (!canAccess(requiredRoles)) {
    if (showFallback) {
      return (
        <div className="min-h-screen bg-gradient-to-br from-blue-50 to-green-50 flex items-center justify-center">
          <div className="bg-white rounded-lg shadow-md p-8 max-w-md mx-4 text-center">
            <div className="text-red-500 text-6xl mb-4">🚫</div>
            <h2 className="text-2xl font-bold text-gray-800 mb-2">
              Acesso Negado
            </h2>
            <p className="text-gray-600 mb-6">
              Você não tem permissão para acessar esta página.
            </p>
            <button
              onClick={() => router.push(fallbackRoute)}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              Voltar
            </button>
          </div>
        </div>
      );
    } else {
      router.push(fallbackRoute);
      return null;
    }
  }

  return <>{children}</>;
};

export default ProtectedRoute;
