'use client';

import React from 'react';
import { useAuth } from '../contexts/AuthContext';
import LoadingSpinner from './ui/LoadingSpinner';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

interface ProtectedLayoutProps {
  children: React.ReactNode;
  requiredRoles?: string[];
  requiredPermissions?: string[];
}

const ProtectedLayout: React.FC<ProtectedLayoutProps> = ({ 
  children, 
  requiredRoles = [], 
  requiredPermissions = [] 
}) => {
  const { isAuthenticated, isLoading, user, hasRole, hasPermission } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      // Ne pas rediriger si on est en train de traiter un code d'autorisation
      const currentUrl = window.location.href;
      const hasAuthCode = currentUrl.includes('code=') && currentUrl.includes('/dashboard');

      if (!hasAuthCode) {
        // Rediriger vers la page de connexion avec l'URL de retour
        const currentPath = window.location.pathname + window.location.search;
        window.location.href = `/api/auth/login?redirect=${encodeURIComponent(currentPath)}`;
      } else {
        console.log('🔄 ProtectedLayout: Redirection ignorée car authentification en cours...');
      }
    }
  }, [isAuthenticated, isLoading, router]);

  useEffect(() => {
    if (isAuthenticated && user) {
      // Vérifier les rôles requis
      if (requiredRoles.length > 0) {
        const hasRequiredRole = requiredRoles.some(role => hasRole(role));
        if (!hasRequiredRole) {
          router.push('/');
          return;
        }
      }

      // Vérifier les permissions requises
      if (requiredPermissions.length > 0) {
        const hasRequiredPermission = requiredPermissions.some(permission => hasPermission(permission));
        if (!hasRequiredPermission) {
          router.push('/');
          return;
        }
      }
    }
  }, [isAuthenticated, user, requiredRoles, requiredPermissions, hasRole, hasPermission, router]);

  // Affichage pendant le chargement
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <LoadingSpinner size="large" />
          <p className="mt-4 text-gray-600">Chargement...</p>
        </div>
      </div>
    );
  }

  // Si pas authentifié, vérifier s'il y a un code d'autorisation en cours
  if (!isAuthenticated) {
    // Si on a un code d'autorisation, laisser le composant se charger pour traiter l'authentification
    if (typeof window !== 'undefined') {
      const currentUrl = window.location.href;
      const hasAuthCode = currentUrl.includes('code=') && currentUrl.includes('/dashboard');

      if (hasAuthCode) {
        console.log('🔓 ProtectedLayout: Autorisant le rendu car code d\'autorisation présent');
        // Laisser le composant se charger pour traiter l'authentification
      } else {
        // Pas de code d'autorisation, afficher le message de redirection
        return (
          <div className="min-h-screen flex items-center justify-center bg-gray-50">
            <div className="text-center">
              <LoadingSpinner size="large" />
              <p className="mt-4 text-gray-600">Redirection vers la connexion...</p>
            </div>
          </div>
        );
      }
    }
  }

  // Si authentifié mais pas les bonnes permissions, ne rien afficher (redirection en cours)
  if (user) {
    if (requiredRoles.length > 0) {
      const hasRequiredRole = requiredRoles.some(role => hasRole(role));
      if (!hasRequiredRole) {
        return (
          <div className="min-h-screen flex items-center justify-center bg-gray-50">
            <div className="text-center">
              <LoadingSpinner size="large" />
              <p className="mt-4 text-gray-600">Vérification des permissions...</p>
            </div>
          </div>
        );
      }
    }

    if (requiredPermissions.length > 0) {
      const hasRequiredPermission = requiredPermissions.some(permission => hasPermission(permission));
      if (!hasRequiredPermission) {
        return (
          <div className="min-h-screen flex items-center justify-center bg-gray-50">
            <div className="text-center">
              <LoadingSpinner size="large" />
              <p className="mt-4 text-gray-600">Vérification des permissions...</p>
            </div>
          </div>
        );
      }
    }
  }

  // Afficher le contenu si tout est OK
  return <>{children}</>;
};

export default ProtectedLayout;
