import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext';
import Sidebar from '../components/Sidebar';
import { Plus, Search, Filter, Eye, Menu, X, RefreshCw, Wifi, WifiOff, Info, Edit2, Trash2 } from 'lucide-react';
import NewLeaveRequestModal from '../components/NewLeaveRequestModal';
import EditLeaveRequestModal from '../components/EditLeaveRequestModal';
import { useMsal } from "@azure/msal-react";
import MedicalDocuments from '../components/MedicalDocuments';
import Joyride, { STATUS } from 'react-joyride';


const Requests = () => {
    const { user } = useAuth();
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [detailedCounters, setDetailedCounters] = useState(null);

    const [showNewRequestModal, setShowNewRequestModal] = useState(false);
    const [showEditRequestModal, setShowEditRequestModal] = useState(false);
    const [requestToEdit, setRequestToEdit] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isRefreshing, setIsRefreshing] = useState(false);

    const [allRequests, setAllRequests] = useState([]);
    const [filteredRequests, setFilteredRequests] = useState([]);
    const [selectedRequest, setSelectedRequest] = useState(null);

    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');

    const [currentPage, setCurrentPage] = useState(1);
    const [requestsPerPage] = useState(10);

    const [showFilters, setShowFilters] = useState(false);

    const [graphToken, setGraphToken] = useState(null);
    const { instance, accounts } = useMsal();
    const userId = user?.id || user?.CollaborateurADId || user?.ID;

    const [lastRefresh, setLastRefresh] = useState(new Date());

    // States pour SSE
    const [sseConnected, setSseConnected] = useState(false);
    const [toasts, setToasts] = useState([]);

    // ⭐ State pour la modal de confirmation de suppression
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [requestToDelete, setRequestToDelete] = useState(null);

    const [isSubmitting, setIsSubmitting] = useState(false);

    // 🎯 STATES POUR LE TUTORIEL
    const [runTour, setRunTour] = useState(false);

    // 🎯 DÉCLENCHER LE TUTORIEL À CHAQUE FOIS
    useEffect(() => {
        if (userId && !isLoading) {
            setTimeout(() => setRunTour(true), 1500);
        }
    }, [userId, isLoading]);

    // 🎯 DÉFINITION DES ÉTAPES DU TUTORIEL
    const tourSteps = [
        {
            target: '[data-tour="nouvelle-demande"]',
            content: '➕ Créez une nouvelle demande de congé en cliquant ici.',
            placement: 'bottom',
        },
        {
            target: '[data-tour="recherche"]',
            content: '🔍 Recherchez vos demandes par type ou statut.',
            placement: 'bottom',
        },
        {
            target: '[data-tour="filtres"]',
            content: '🎯 Filtrez vos demandes par statut ou type de congé.',
            placement: 'bottom',
        },
        {
            target: '[data-tour="liste-demandes"]',
            content: '📋 Consultez la liste de toutes vos demandes ici.',
            placement: 'top',
        },
    ];

    // 🎯 GÉRER LA FIN DU TOUR
    const handleJoyrideCallback = (data) => {
        const { status } = data;
        const finishedStatuses = [STATUS.FINISHED, STATUS.SKIPPED];
        if (finishedStatuses.includes(status)) {
            setRunTour(false);
        }
    };

    useEffect(() => {
        if (accounts.length > 0) {
            const request = {
                scopes: ["User.Read", "Mail.Send"],
                account: accounts[0],
            };

            instance.acquireTokenSilent(request)
                .then((response) => {
                    setGraphToken(response.accessToken);
                })
                .catch((err) => {
                    console.error("❌ Erreur récupération token Graph:", err);
                });
        }
    }, [accounts, instance]);

    const fetchDetailedCounters = async () => {
        try {
            const response = await fetch(`/api/getDetailedLeaveCounters?user_id=${userId}`);
            const data = await response.json();

            if (data.success) {
                setDetailedCounters(data.data);
            } else {
                console.error("Erreur compteurs:", data.message);
            }
        } catch (error) {
            console.error('💥 Erreur compteurs:', error);
        }
    };

    const fetchAllRequests = async () => {
        try {
            const url = `/api/getRequests?user_id=${userId}`;
            const response = await fetch(url);
            const text = await response.text();
            let data;
            try {
                data = JSON.parse(text);
            } catch {
                throw new Error('Le serveur PHP ne répond pas correctement');
            }
            if (data.success) {
                console.log('🔍 DEBUG - Requests reçues:', data.requests);
                if (data.requests && data.requests.length > 0) {
                    console.log('🔍 DEBUG - Premier request:', data.requests[0]);
                }
                setAllRequests(data.requests || []);
            } else {
                throw new Error(data.message || 'Erreur lors de la récupération des demandes');
            }
        } catch (error) {
            console.error('Erreur requêtes:', error);
        }
    };

    // Fonction de rafraîchissement unifiée
    const refreshAllData = useCallback(async () => {
        if (!userId) return;

        console.log('🔄 Rafraîchissement des données...');
        if (!isLoading) setIsRefreshing(true);

        try {
            await Promise.all([
                fetchDetailedCounters(),
                fetchAllRequests()
            ]);
            setLastRefresh(new Date());
            console.log('✅ Données rafraîchies');
        } catch (error) {
            console.error('❌ Erreur lors du rafraîchissement:', error);
        } finally {
            setIsLoading(false);
            setIsRefreshing(false);
        }
    }, [userId]);

    // Fonction pour afficher des toasts
    const showToast = useCallback((message, type = 'info') => {
        const id = Date.now();
        const newToast = { id, message, type };

        setToasts(prev => [...prev, newToast]);

        // Auto-remove après 5 secondes
        setTimeout(() => {
            setToasts(prev => prev.filter(t => t.id !== id));
        }, 5000);
    }, []);

    // ⭐ FONCTION CORRIGÉE : Modifier une demande
    const handleEditRequest = (request) => {
        console.log('🔍 DEBUG - Request à éditer:', request);
        console.log('🔍 DEBUG - Request ID:', request.id);
        console.log('🔍 DEBUG - Request startDate:', request.startDate);
        console.log('🔍 DEBUG - Request endDate:', request.endDate);
        console.log('🔍 DEBUG - Request type:', request.type);
        console.log('🔍 DEBUG - Request reason:', request.reason);

        setRequestToEdit(request);
        setShowEditRequestModal(true);

        console.log('✅ Modal d\'édition devrait s\'ouvrir');
    };

    // ⭐ FONCTION : Supprimer/Annuler une demande
    const handleDeleteRequest = async (requestId) => {
        try {
            setIsLoading(true);

            console.log('🗑️ Début annulation, ID:', requestId);

            // Chercher la demande dans allRequests
            let request = allRequests.find(r => r.id === requestId);

            if (!request) {
                console.log('⚠️ Demande non trouvée dans l\'état local, récupération via API...');

                try {
                    const response = await fetch(`/api/getRequests?user_id=${userId}`);
                    const result = await response.json();

                    if (result.success && result.requests) {
                        request = result.requests.find(r => r.id === requestId);
                    }
                } catch (err) {
                    console.error('Erreur récupération demande:', err);
                }
            }

            if (!request) {
                showToast('❌ Demande introuvable', 'error');
                setIsLoading(false);
                return;
            }

            console.log('📋 Demande trouvée:', request);

            // Vérifier la date de début
            const dateDebut = new Date(request.startDate);
            const aujourdhui = new Date();
            aujourdhui.setHours(0, 0, 0, 0);
            dateDebut.setHours(0, 0, 0, 0);

            console.log('📅 Date début:', dateDebut.toLocaleDateString('fr-FR'));
            console.log('📅 Aujourd\'hui:', aujourdhui.toLocaleDateString('fr-FR'));

            if (dateDebut <= aujourdhui) {
                showToast(
                    `❌ Impossible d'annuler : la date de début (${dateDebut.toLocaleDateString('fr-FR')}) est déjà passée`,
                    'error'
                );
                setIsLoading(false);
                return;
            }

            // ⭐ CONFIRMATION AVEC MODAL
            setRequestToDelete(request);
            setShowDeleteConfirm(true);
            setIsLoading(false);

        } catch (error) {
            console.error('❌ Erreur annulation:', error);
            showToast(`Erreur: ${error.message}`, 'error');
            setIsLoading(false);
        }
    };

    // Fonction helper pour formater les dates
    const formatDate = (dateStr) => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return date.toLocaleDateString('fr-FR');
    };

    // ⭐ FONCTION : Confirmer la suppression
    const confirmDeleteRequest = async () => {
        if (!requestToDelete) return;

        setIsSubmitting(true);

        try {
            const requestData = {
                requestId: requestToDelete.id,
                userId: userId,
                userEmail: user.email,
                userName: `${user.prenom} ${user.nom}`,
                accessToken: graphToken
            };

            console.log('📤 Envoi requête:', requestData);

            const response = await fetch('/api/deleteRequest', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('📥 Réponse API:', result);

            if (result.success) {
                // ✅ Succès
                showToast('✅ Demande annulée avec succès', 'success');

                if (result.counterRestored && result.repartition) {
                    // Afficher les détails de la restauration
                    const repartitionText = result.repartition
                        .map(r => `${r.type}: ${r.jours}j${r.periode !== 'Journée entière' ? ` (${r.periode})` : ''}`)
                        .join(', ');

                    showToast(`📊 Compteurs restaurés: ${repartitionText}`, 'info');
                }

                if (result.emailsSent) {
                    if (result.emailsSent.collaborateur) {
                        showToast('📧 Email de confirmation envoyé', 'info');
                    }
                    if (result.emailsSent.manager) {
                        showToast('📧 Manager notifié par email', 'info');
                    }
                }

                // ⭐ Rafraîchir les données
                await refreshAllData();

            } else {
                // ❌ Erreur
                showToast(result.message || 'Erreur lors de l\'annulation', 'error');
            }

        } catch (error) {
            console.error('❌ Erreur annulation:', error);
            showToast(`Erreur serveur: ${error.message}`, 'error');
        } finally {
            setIsSubmitting(false);
            setShowDeleteConfirm(false);
            setRequestToDelete(null);

            // Fermer les détails si c'était la demande affichée
            if (selectedRequest?.id === requestToDelete?.id) {
                setSelectedRequest(null);
            }
        }
    };

    // Connexion SSE
    useEffect(() => {
        if (!userId) return;

        console.log('🔌 Connexion SSE au serveur collaborateurs...');

        const eventSource = new EventSource(`/api/events/collaborateur?user_id=${userId}`);

        eventSource.onopen = () => {
            console.log('✅ SSE connecté');
            setSseConnected(true);
        };

        eventSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                console.log('📩 SSE reçu:', data);

                switch (data.type) {
                    case 'connected':
                        console.log('✅ Connexion SSE établie:', data.message);
                        break;

                    case 'heartbeat':
                        break;

                    case 'demande-validated-rh':
                        console.log(`🔔 Validation RH reçue: ${data.statut}`);

                        if (data.statut === 'Validée') {
                            showToast('✅ Votre demande a été VALIDÉE !', 'success');
                        } else if (data.statut === 'Refusée') {
                            showToast('❌ Votre demande a été REFUSÉE', 'error');
                        }

                        refreshAllData();
                        break;

                    case 'compteur-updated':
                        console.log('🔄 Compteurs mis à jour');
                        fetchDetailedCounters();
                        break;

                    default:
                        console.log('📩 Événement SSE:', data);
                }
            } catch (error) {
                console.error('❌ Erreur parsing SSE:', error);
            }
        };

        eventSource.onerror = (error) => {
            console.error('❌ Erreur SSE:', error);
            setSseConnected(false);
        };

        return () => {
            console.log('🔌 Fermeture connexion SSE');
            eventSource.close();
        };
    }, [userId, refreshAllData, showToast]);

    useEffect(() => {
        if (userId) {
            refreshAllData();
        }
    }, [userId, refreshAllData]);

    useEffect(() => {
        let filtered = allRequests;

        if (searchTerm) {
            filtered = filtered.filter(req =>
                req.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
                req.status.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }

        if (statusFilter !== 'all') {
            filtered = filtered.filter(req => req.status === statusFilter);
        }

        if (typeFilter !== 'all') {
            filtered = filtered.filter(req => req.type === typeFilter);
        }

        setFilteredRequests(filtered);
        setCurrentPage(1);
    }, [allRequests, searchTerm, statusFilter, typeFilter]);

    const indexOfLastRequest = currentPage * requestsPerPage;
    const indexOfFirstRequest = indexOfLastRequest - requestsPerPage;
    const currentRequests = filteredRequests.slice(indexOfFirstRequest, indexOfLastRequest);
    const totalPages = Math.ceil(filteredRequests.length / requestsPerPage);

    const paginate = (pageNumber) => setCurrentPage(pageNumber);

    const getStatusColor = (status) => {
        switch (status) {
            case 'En attente': return 'bg-yellow-100 text-yellow-800';
            case 'Validée': return 'bg-green-100 text-green-800';
            case 'Refusée': return 'bg-red-100 text-red-800';
            case 'Annulée': return 'bg-gray-100 text-gray-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    };

    const handleViewRequest = (request) => {
        setSelectedRequest(request);
    };

    const handleCloseDetails = () => {
        setSelectedRequest(null);
    };

    const handleRefresh = () => {
        refreshAllData();
    };

    return (
        <div className="min-h-screen bg-gray-50">

            {/* 🎯 TUTORIEL INTERACTIF */}
            <Joyride
                steps={tourSteps}
                run={runTour}
                continuous
                showProgress={false}
                showSkipButton
                callback={handleJoyrideCallback}
                styles={{ options: { primaryColor: '#0891b2', zIndex: 10000 } }}
                tooltipComponent={({ continuous, index, step, backProps, primaryProps, skipProps, tooltipProps, size }) => (
                    <div {...tooltipProps} style={{ backgroundColor: 'white', borderRadius: '12px', padding: '20px', maxWidth: '350px', boxShadow: '0 10px 25px rgba(0,0,0,0.15)', fontSize: '14px' }}>
                        <div style={{ marginBottom: '15px', color: '#374151' }}>{step.content}</div>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '12px', borderTop: '1px solid #e5e7eb' }}>
                            <span style={{ fontSize: '13px', color: '#6b7280', fontWeight: '500' }}>Étape {index + 1} sur {size}</span>
                            <div style={{ display: 'flex', gap: '8px' }}>
                                {index > 0 && <button {...backProps} style={{ padding: '6px 12px', borderRadius: '6px', border: '1px solid #d1d5db', backgroundColor: 'white', color: '#6b7280', cursor: 'pointer', fontSize: '13px', fontWeight: '500' }}>Retour</button>}
                                {continuous && index < size - 1 && <button {...primaryProps} style={{ padding: '6px 16px', borderRadius: '6px', border: 'none', backgroundColor: '#0891b2', color: 'white', cursor: 'pointer', fontSize: '13px', fontWeight: '500' }}>Suivant</button>}
                                {(!continuous || index === size - 1) && <button {...primaryProps} style={{ padding: '6px 16px', borderRadius: '6px', border: 'none', backgroundColor: '#0891b2', color: 'white', cursor: 'pointer', fontSize: '13px', fontWeight: '500' }}>Terminer</button>}
                                <button {...skipProps} style={{ padding: '6px 10px', borderRadius: '6px', border: 'none', backgroundColor: 'transparent', color: '#9ca3af', cursor: 'pointer', fontSize: '12px' }}>Passer</button>
                            </div>
                        </div>
                    </div>
                )}
            />

            <Sidebar isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />

            {/* Toast container */}
            <div className="fixed top-4 right-4 z-50 space-y-2">
                {toasts.map(toast => (
                    <div
                        key={toast.id}
                        className={`px-4 py-3 rounded-lg shadow-lg ${toast.type === 'success' ? 'bg-green-500 text-white' :
                            toast.type === 'error' ? 'bg-red-500 text-white' :
                                toast.type === 'warning' ? 'bg-yellow-500 text-white' :
                                    'bg-blue-500 text-white'
                            } animate-slideInRight`}
                        style={{ animation: 'slideInRight 0.3s ease-out' }}
                    >
                        {toast.message}
                    </div>
                ))}
            </div>

            {/* Modal de confirmation de suppression */}
            {showDeleteConfirm && requestToDelete && (
                <div className="fixed inset-0 z-50 flex items-center justify-center">
                    <div className="absolute inset-0 bg-black bg-opacity-50" onClick={() => !isSubmitting && setShowDeleteConfirm(false)}></div>
                    <div className="relative bg-white rounded-xl shadow-xl p-6 max-w-md w-full mx-4">
                        <h3 className="text-lg font-semibold mb-4 text-gray-900">
                            ⚠️ Confirmer l'annulation
                        </h3>

                        <div className="space-y-3 mb-6">
                            <p className="text-gray-700">
                                Voulez-vous annuler cette demande de congé ?
                            </p>

                            <div className="bg-gray-50 p-4 rounded-lg space-y-2 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-gray-600">Type :</span>
                                    <span className="font-medium">{requestToDelete.type}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-gray-600">Période :</span>
                                    <span className="font-medium">{requestToDelete.dateDisplay}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-gray-600">Durée :</span>
                                    <span className="font-medium">{requestToDelete.days} jour(s)</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-gray-600">Statut :</span>
                                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${getStatusColor(requestToDelete.status)}`}>
                                        {requestToDelete.status}
                                    </span>
                                </div>
                            </div>

                            {(requestToDelete.status === 'Validée' || requestToDelete.status === 'Validé') && (
                                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
                                    <p className="font-medium">ℹ️ Information</p>
                                    <p className="mt-1">Cette demande a été validée. Vos compteurs seront automatiquement restaurés.</p>
                                </div>
                            )}
                        </div>

                        <div className="flex gap-3 justify-end">
                            <button
                                onClick={() => setShowDeleteConfirm(false)}
                                disabled={isSubmitting}
                                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 disabled:opacity-50"
                            >
                                Annuler
                            </button>
                            <button
                                onClick={confirmDeleteRequest}
                                disabled={isSubmitting}
                                className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 flex items-center gap-2"
                            >
                                {isSubmitting ? (
                                    <>
                                        <RefreshCw className="w-4 h-4 animate-spin" />
                                        Annulation...
                                    </>
                                ) : (
                                    <>
                                        <Trash2 className="w-4 h-4" />
                                        Confirmer l'annulation
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            <div className="flex-1 lg:ml-64">
                <div className="p-4 lg:p-8 max-w-7xl mx-auto">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-6">
                        <div className="flex items-center gap-3">
                            <button onClick={() => setSidebarOpen(true)} className="lg:hidden p-2">
                                <Menu className="w-6 h-6" />
                            </button>
                            <div>
                                <h1 className="text-2xl lg:text-3xl font-bold text-gray-900">Mes demandes</h1>
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={handleRefresh}
                                disabled={isRefreshing}
                                className={`p-2 text-gray-600 hover:bg-gray-100 rounded-lg ${isRefreshing ? 'opacity-50 cursor-not-allowed' : ''}`}
                                title="Rafraîchir"
                            >
                                <RefreshCw className={`w-5 h-5 ${isRefreshing ? 'animate-spin' : ''}`} />
                            </button>
                            <button
                                data-tour="nouvelle-demande"
                                onClick={() => setShowNewRequestModal(true)}
                                className="bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center gap-2 hover:bg-blue-700 text-sm lg:text-base"
                            >
                                <Plus className="w-5 h-5" /> Nouvelle demande
                            </button>
                        </div>
                    </div>

                    {/* Main content */}
                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        {/* Left: list */}
                        <div className="lg:col-span-2">
                            {/* Filters */}
                            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-4">
                                <div className="flex flex-col sm:flex-row gap-3">
                                    <div className="flex-1">
                                        <div className="flex-1 relative" data-tour="recherche">
                                            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                                            <input
                                                type="text"
                                                placeholder="Rechercher..."
                                                value={searchTerm}
                                                onChange={(e) => setSearchTerm(e.target.value)}
                                                className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            />
                                        </div>
                                    </div>
                                    <button
                                        data-tour="filtres"
                                        onClick={() => setShowFilters(!showFilters)}
                                        className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg hover:bg-gray-50"
                                    >
                                        <Filter className="w-5 h-5" />
                                        Filtres
                                    </button>
                                </div>

                                {showFilters && (
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3 pt-3 border-t">
                                        <select
                                            value={statusFilter}
                                            onChange={(e) => setStatusFilter(e.target.value)}
                                            className="px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        >
                                            <option value="all">Tous les statuts</option>
                                            <option value="En attente">En attente</option>
                                            <option value="Validée">Validée</option>
                                            <option value="Refusée">Refusée</option>
                                            <option value="Annulée">Annulée</option>
                                        </select>
                                        <select
                                            value={typeFilter}
                                            onChange={(e) => setTypeFilter(e.target.value)}
                                            className="px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        >
                                            <option value="all">Tous les types</option>
                                            <option value="Congé payé">Congé(s) payé(s)</option>
                                            <option value="RTT">RTT</option>
                                            <option value="Arrêt maladie">Arrêt maladie</option>
                                            <option value="Récupération">Récupération</option>
                                        </select>
                                    </div>
                                )}
                            </div>

                            {/* Requests list */}
                            {isLoading ? (
                                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8 text-center">
                                    <RefreshCw className="w-8 h-8 animate-spin mx-auto text-blue-600 mb-2" />
                                    <p className="text-gray-500">Chargement...</p>
                                </div>
                            ) : currentRequests.length === 0 ? (
                                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8 text-center">
                                    <Info className="w-12 h-12 mx-auto text-gray-300 mb-3" />
                                    <p className="text-gray-500">Aucune demande trouvée</p>
                                </div>
                            ) : (
                                <>
                                    <div className="space-y-3" data-tour="liste-demandes">
                                        {currentRequests.map((request) => (
                                            <div key={request.id} className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 hover:shadow-md transition-shadow">
                                                <div className="flex justify-between items-start mb-2">
                                                    <div className="flex-1">
                                                        <h3 className="font-semibold text-gray-900">{request.type}</h3>
                                                        <p className="text-sm text-gray-600">{request.dateDisplay}</p>
                                                    </div>
                                                    <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${getStatusColor(request.status)}`}>
                                                        {request.status}
                                                    </span>
                                                </div>

                                                <div className="flex items-center gap-2 text-sm text-gray-500 mb-3">
                                                    <span className="bg-gray-100 px-2 py-1 rounded">{request.days} jour(s)</span>
                                                </div>

                                                <div className="mt-3 flex justify-between items-center text-sm">
                                                    <span className="text-gray-500">{request.submittedDisplay}</span>
                                                    <div className="flex items-center gap-2">
                                                        {/* ⭐ Bouton Modifier - Plus de restriction sur le statut */}
                                                        <button
                                                            onClick={() => handleEditRequest(request)}
                                                            className="text-blue-600 hover:text-blue-700 flex items-center gap-1 px-2 py-1 hover:bg-blue-50 rounded"
                                                            title="Modifier"
                                                        >
                                                            <Edit2 className="w-4 h-4" />
                                                            <span className="hidden sm:inline">Modifier</span>
                                                        </button>

                                                        {/* Bouton Annuler */}
                                                        {request.status !== 'Annulée' && request.status !== 'Refusée' && (
                                                            <button
                                                                onClick={() => handleDeleteRequest(request.id)}
                                                                className="text-orange-600 hover:text-orange-700 flex items-center gap-1 px-2 py-1 hover:bg-orange-50 rounded"
                                                                title="Annuler"
                                                            >
                                                                <X className="w-4 h-4" />
                                                                <span className="hidden sm:inline">Annuler</span>
                                                            </button>
                                                        )}

                                                        {/* Bouton Voir */}
                                                        <button
                                                            onClick={() => handleViewRequest(request)}
                                                            className="text-gray-600 hover:text-gray-700 flex items-center gap-1 px-2 py-1 hover:bg-gray-50 rounded"
                                                        >
                                                            <Eye className="w-4 h-4" />
                                                            <span className="hidden sm:inline">Voir</span>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    {/* Pagination */}
                                    {totalPages > 1 && (
                                        <div className="mt-4 flex justify-center gap-2">
                                            {[...Array(totalPages)].map((_, i) => (
                                                <button
                                                    key={i}
                                                    onClick={() => paginate(i + 1)}
                                                    className={`px-3 py-1 rounded ${currentPage === i + 1
                                                        ? 'bg-blue-600 text-white'
                                                        : 'bg-white border border-gray-200 text-gray-700 hover:bg-gray-50'
                                                        }`}
                                                >
                                                    {i + 1}
                                                </button>
                                            ))}
                                        </div>
                                    )}
                                </>
                            )}
                        </div>

                        {/* Right: details */}
                        <div className="hidden lg:block">
                            {selectedRequest ? (
                                <div className="bg-white rounded-xl shadow-md border border-gray-100 p-6 sticky top-20">
                                    <div className="flex justify-between items-start mb-6">
                                        <h3 className="text-lg font-semibold">Détails de la demande</h3>
                                        <button onClick={handleCloseDetails} className="text-gray-500 hover:text-gray-800 p-2">
                                            <X className="w-4 h-4" />
                                        </button>
                                    </div>

                                    <div className="space-y-4 text-sm text-gray-700">
                                        <div>
                                            <p className="text-gray-500">Type</p>
                                            <p className="text-base font-medium text-gray-900">{selectedRequest.type}</p>
                                        </div>
                                        <div>
                                            <p className="text-gray-500">Dates</p>
                                            <p className="text-base font-medium text-gray-900">{selectedRequest.dateDisplay}</p>
                                        </div>
                                        <div>
                                            <p className="text-gray-500">Nombre de jours</p>
                                            <p className="text-base font-medium text-gray-900">{selectedRequest.days}</p>
                                        </div>
                                        <div>
                                            <p className="text-gray-500">Statut</p>
                                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${getStatusColor(selectedRequest.status)}`}>
                                                {selectedRequest.status}
                                            </span>
                                        </div>
                                        {selectedRequest.reason && (
                                            <div>
                                                <p className="text-gray-500">Motif</p>
                                                <p className="italic">{selectedRequest.reason}</p>
                                            </div>
                                        )}
                                        {(selectedRequest.status === 'Validée' || selectedRequest.status === 'Refusée') && selectedRequest.validationComment && (
                                            <div>
                                                <p className="text-gray-500">{selectedRequest.status === 'Validée' ? 'Commentaire de validation' : 'Motif du refus'}</p>
                                                <p className="italic text-sm bg-gray-50 p-3 rounded-lg border-l-4" style={{ borderLeftColor: selectedRequest.status === 'Validée' ? '#10b981' : '#ef4444' }}>{selectedRequest.validationComment}</p>
                                            </div>
                                        )}

                                        <MedicalDocuments demandeId={selectedRequest.id} />
                                    </div>

                                    {/* Actions dans la sidebar */}
                                    <div className="mt-6 pt-4 border-t space-y-2">
                                        {/* ⭐ Bouton Modifier - Toujours visible */}
                                        <button
                                            onClick={() => handleEditRequest(selectedRequest)}
                                            className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                                        >
                                            <Edit2 className="w-4 h-4" />
                                            Modifier cette demande
                                        </button>

                                        {/* Bouton Annuler */}
                                        {selectedRequest.status !== 'Annulée' && selectedRequest.status !== 'Refusée' && (
                                            <button
                                                onClick={() => handleDeleteRequest(selectedRequest.id)}
                                                className="w-full flex items-center justify-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
                                            >
                                                <X className="w-4 h-4" />
                                                Annuler cette demande
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ) : (
                                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 text-sm text-gray-500">
                                    Sélectionnez une demande pour voir les détails
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Modals */}
                {showNewRequestModal && detailedCounters && (
                    <NewLeaveRequestModal
                        onClose={() => setShowNewRequestModal(false)}
                        availableLeaveCounters={{
                            availableCP_N: detailedCounters.cpN?.solde || 0,
                            totalCP_N: detailedCounters.cpN?.acquis || 0,
                            availableCP_N1: detailedCounters.cpN1?.solde || 0,
                            availableRTT_N: detailedCounters.rttN?.solde || 0,
                            totalRTT_N: detailedCounters.rttN?.acquis || 0,
                            availableRTT_N1: 0,
                            availableABS: 0,
                            availableCP: (detailedCounters.cpN1?.solde || 0) + (detailedCounters.cpN?.solde || 0),
                            availableRTT: detailedCounters.rttN?.solde || 0,
                            availableRecup: detailedCounters?.recupN?.solde || 0,
                            availableRecup_N: detailedCounters?.recupN?.solde || 0
                        }}
                        accessToken={graphToken}
                        userId={userId}
                        userEmail={user.email}
                        userRole={user.role}
                        userName={`${user.prenom} ${user.nom}`}
                        onRequestSubmitted={() => {
                            refreshAllData();
                        }}
                    />
                )}

                {/* ⭐ MODAL D'ÉDITION CORRIGÉE */}
                {showEditRequestModal && requestToEdit && detailedCounters && (
                    <EditLeaveRequestModal
                        isOpen={showEditRequestModal}
                        onClose={() => {
                            console.log('❌ Fermeture du modal d\'édition');
                            setShowEditRequestModal(false);
                            setRequestToEdit(null);
                        }}
                        request={requestToEdit}
                        availableLeaveCounters={{
                            availableCP_N: detailedCounters.cpN?.solde || 0,
                            totalCP_N: detailedCounters.cpN?.acquis || 0,
                            availableCP_N1: detailedCounters.cpN1?.solde || 0,
                            availableRTT_N: detailedCounters.rttN?.solde || 0,
                            totalRTT_N: detailedCounters.rttN?.acquis || 0,
                            availableRTT_N1: 0,
                            availableABS: 0,
                            availableCP: (detailedCounters.cpN1?.solde || 0) + (detailedCounters.cpN?.solde || 0),
                            availableRTT: detailedCounters.rttN?.solde || 0,
                            availableRecup: detailedCounters?.recupN?.solde || 0,
                            availableRecup_N: detailedCounters?.recupN?.solde || 0
                        }}
                        accessToken={graphToken}
                        userId={userId}
                        userEmail={user.email}
                        userName={`${user.prenom} ${user.nom}`}
                        onRequestUpdated={() => {
                            console.log('✅ Demande mise à jour, rafraîchissement...');
                            refreshAllData();
                            setShowEditRequestModal(false);
                            setRequestToEdit(null);
                        }}
                    />
                )}
            </div>

            {/* Styles */}
            <style>{`
                @keyframes slideInRight {
                    from {
                        transform: translateX(400px);
                        opacity: 0;
                    }
                    to {
                        transform: translateX(0);
                        opacity: 1;
                    }
                }
            `}</style>
        </div>
    );
};

export default Requests;