import { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { LoadingState } from '@/components/common/LoadingState';

interface ProtectedRouteProps {
  children: ReactNode;
  requiredRoles?: string[];
  requireAnyRole?: boolean;
}

export function ProtectedRoute({
  children,
  requiredRoles,
  requireAnyRole = false,
}: ProtectedRouteProps) {
  const { isAuthenticated, loading, hasRole, hasAnyRole } = useAuth();

  if (loading) {
    return <LoadingState />;
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  // Verificar permissões se necessário
  if (requiredRoles && requiredRoles.length > 0) {
    const hasPermission = requireAnyRole
      ? hasAnyRole(requiredRoles)
      : requiredRoles.every((role) => hasRole(role));

    if (!hasPermission) {
      return (
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-destructive mb-2">
              Acesso Negado
            </h1>
            <p className="text-muted-foreground">
              Você não tem permissão para acessar esta página.
            </p>
          </div>
        </div>
      );
    }
  }

  return <>{children}</>;
}

