
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useEffect } from "react";

interface ProtectedRouteProps {
  children: React.ReactNode;
  allowedRoles?: ('planner' | 'traveler')[];
}

export function ProtectedRoute({ children, allowedRoles = [] }: ProtectedRouteProps) {
  const { isAuthenticated, currentUser, isLoading } = useAuth();
  const location = useLocation();

  useEffect(() => {
    console.group('🛡️ ProtectedRoute - Vérification d\'accès');
    console.info('URL actuelle:', location.pathname);
    console.info('Authenticated:', isAuthenticated);
    console.info('Role:', currentUser?.role || 'non défini');
    console.info('Loading:', isLoading);

    if (allowedRoles.length > 0) {
      console.info('Rôles autorisés:', allowedRoles);
      console.info('Accès autorisé:', currentUser && allowedRoles.includes(currentUser.role));
    } else {
      console.info('Aucune restriction de rôle, authentification uniquement');
    }

    console.groupEnd();
  }, [isAuthenticated, currentUser, isLoading, location.pathname, allowedRoles]);

  if (isLoading) {
    return (
      <div className="flex justify-center items-center min-h-[50vh]">
        <div className="animate-pulse text-lg">Chargement...</div>
      </div>
    );
  }

  if (!isAuthenticated) {
    console.warn('⚠️ Non authentifié, redirection vers /login');
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  if (allowedRoles.length > 0 && currentUser && !allowedRoles.includes(currentUser.role)) {
    // Rediriger vers le dashboard approprié selon le rôle
    const redirectPath = currentUser.role === 'planner' ? '/dashboard' : '/voyageur/dashboard';
    console.warn(`⚠️ Accès refusé (rôle: ${currentUser.role}), redirection vers ${redirectPath}`);
    return <Navigate to={redirectPath} replace />;
  }

  return <>{children}</>;
}
