import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import Sidebar from '../components/Sidebar';
import { Calendar as CalendarIcon, Clock, Users, TrendingUp, Plus, Settings, RefreshCw, Search, Filter, Eye, Edit, Trash2, Menu } from 'lucide-react';
import NewLeaveRequestModal from '../components/NewLeaveRequestModal';

const Requests = () => {
    const { user } = useAuth();
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [leaveCounters, setLeaveCounters] = useState({
        availableCP: 0,
        availableRTT: 0,
        availableABS: 0,
        rttInProcess: 0,
        absenteism: 0
    });
    const [showNewRequestModal, setShowNewRequestModal] = useState(false);
    const [showAdminPanel, setShowAdminPanel] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [allRequests, setAllRequests] = useState([]);
    const [filteredRequests, setFilteredRequests] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [typeFilter, setTypeFilter] = useState('all');
    const [currentPage, setCurrentPage] = useState(1);
    const [requestsPerPage] = useState(10);

    useEffect(() => {
        if (user?.id) {
            fetchLeaveCounters();
            fetchAllRequests();
        }
    }, [user]);

    // Filtrage des demandes
    useEffect(() => {
        let filtered = allRequests;

        // Filtre par terme de recherche
        if (searchTerm) {
            filtered = filtered.filter(request =>
                request.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
                request.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
                request.dateDisplay.includes(searchTerm)
            );
        }

        // Filtre par statut
        if (statusFilter !== 'all') {
            filtered = filtered.filter(request => request.status === statusFilter);
        }

        // Filtre par type
        if (typeFilter !== 'all') {
            if (typeFilter === 'Autres') {
                const otherTypes = ['Récup', 'Congés sans solde', 'Congés pour évènement familial', 'Congé maternité', 'Congé paternité', 'Congé parental', 'Congé parental à temps partiel'];
                filtered = filtered.filter(request => otherTypes.includes(request.type));
            } else {
                filtered = filtered.filter(request => request.type === typeFilter);
            }
        }

        setFilteredRequests(filtered);
        setCurrentPage(1); // Reset à la première page lors du filtrage
    }, [allRequests, searchTerm, statusFilter, typeFilter]);

    const fetchLeaveCounters = async () => {
        try {
            const response = await fetch(`http://localhost/GTA/project/public/getLeaveCounters.php?user_id=${user.id}`);
            const text = await response.text();
            console.log(' Requests - Réponse brute compteurs:', text);

            let data;
            try {
                data = JSON.parse(text);
            } catch (parseError) {
                console.error(' Requests - Réponse non-JSON:', text.substring(0, 200));
                throw new Error('Le serveur PHP ne répond pas correctement');
            }

            if (data.success) {
                setLeaveCounters(data.counters);
            } else {
                throw new Error(data.message || 'Erreur lors de la récupération des compteurs');
            }
        } catch (error) {
            console.error('Erreur lors de la récupération des compteurs:', error);
        }
    };

    const fetchAllRequests = async () => {
        console.log('Requests - Début fetchAllRequests pour user:', user?.id);

        try {
            const url = `http://localhost/GTA/project/public/getRequests.php?user_id=${user.id}`;
            console.log(' Requests - URL appelée:', url);

            const response = await fetch(url);
            const text = await response.text();
            console.log(' Requests - Réponse brute:', text);

            const data = JSON.parse(text);
            console.log(' Requests - Données parsées:', data);

            if (data.success) {
                console.log(' Requests - Demandes récupérées:', data.requests?.length);
                setAllRequests(data.requests || []);
            } else {
                throw new Error(data.message || 'Erreur lors de la récupération des demandes');
            }
        } catch (error) {
            console.error(' Requests - Erreur:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleResetCounters = async () => {
        if (!confirm(' ATTENTION !\n\nCette action va réinitialiser TOUS les compteurs de congés selon les règles de gestion :\n\n• Congés Payés : 25 jours (exercice 01/06 au 31/05)\n• RTT : 10 jours pour 2025 (exercice 01/01 au 31/12)\n• Congés Maladie : 0 jours\n\nCette action est IRRÉVERSIBLE !\n\nÊtes-vous sûr de vouloir continuer ?')) {
            return;
        }

        try {
            const response = await fetch('http://localhost/GTA/project/public/resetLeaveCounters.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ manual_reset: true }),
            });

            const data = await response.json();

            if (data.success) {
                alert(` Réinitialisation réussie !\n\n• ${data.details.employees_updated} employés mis à jour\n• Exercice CP : ${data.details.leave_year}\n• Année RTT : ${data.details.rtt_year}\n• Date : ${data.details.reset_date}`);
                fetchLeaveCounters();
            } else {
                alert(` Erreur lors de la réinitialisation :\n${data.message}`);
            }
        } catch (error) {
            console.error('Erreur:', error);
            alert(' Erreur de connexion au serveur');
        }
    };

    const openManualResetPage = () => {
        window.open('http://localhost/GTA/project/public/manualResetCounters.php', '_blank');
    };

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

    // Pagination
    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 handleViewRequest = (request) => {
        alert(`Détails de la demande:\n\nType: ${request.type}\nDates: ${request.dateDisplay}\nJours: ${request.days}\nStatut: ${request.status}\nMotif: ${request.reason}`);
    };

    const handleEditRequest = (request) => {
        if (request.status !== 'En attente') {
            alert('Seules les demandes en attente peuvent être modifiées.');
            return;
        }
        alert('Fonctionnalité de modification en cours de développement.');
    };

    const handleDeleteRequest = (request) => {
        if (request.status !== 'En attente') {
            alert('Seules les demandes en attente peuvent être supprimées.');
            return;
        }
        if (confirm(`Êtes-vous sûr de vouloir supprimer cette demande de ${request.type} ?`)) {
            alert('Fonctionnalité de suppression en cours de développement.');
        }
    };

    if (isLoading) {
        return (
            <div className="min-h-screen bg-gray-50">
                <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
                <div className="lg:ml-60 flex items-center justify-center min-h-screen">
                    <div className="text-center">
                        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                        <p className="text-gray-600">Chargement des données...</p>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 flex">
            <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />

            <div className="flex-1 lg:ml-60 p-4 lg:p-8">
                {/* Mobile menu button */}
                <div className="lg:hidden mb-4">
                    <button
                        onClick={() => setSidebarOpen(true)}
                        className="p-2 rounded-lg bg-white shadow-sm border border-gray-200"
                    >
                        <Menu className="w-6 h-6" />
                    </button>
                </div>

                {/* Header */}
                <div className="flex justify-between items-center mb-8">
                    <div>
                        <h1 className="text-2xl lg:text-3xl font-bold text-gray-900 mb-2">
                            Mes Demandes de Congés
                        </h1>
                        <p className="text-sm lg:text-base text-gray-600">
                            Gérez toutes vos demandes de congés
                        </p>
                    </div>
                    <div className="flex gap-2 lg:gap-3">
                   
                        <button
                            onClick={() => setShowNewRequestModal(true)}
                            className="bg-blue-600 text-white px-3 lg:px-6 py-2 lg:py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors flex items-center gap-2"
                        >
                            <Plus className="w-5 h-5" />
                            <span className="hidden sm:inline">Nouvelle demande</span>
                            <span className="sm:hidden">Nouveau</span>
                        </button>
                    </div>
                </div>

                {/* Admin Panel */}
                {showAdminPanel && (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                                <Settings className="w-5 h-5" />
                                Administration
                            </h2>
                            <button
                                onClick={() => setShowAdminPanel(false)}
                                className="text-gray-400 hover:text-gray-600"
                            >
                                ✕
                            </button>
                        </div>

                        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
                            <h3 className="font-medium text-yellow-800 mb-2">⚠️ Zone d'administration</h3>
                            <p className="text-yellow-700 text-sm">
                                Ces actions affectent tous les utilisateurs du système. Utilisez avec précaution.
                            </p>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <button
                                onClick={handleResetCounters}
                                className="flex items-center gap-3 p-4 border border-red-200 rounded-lg hover:bg-red-50 transition-colors text-left"
                            >
                                <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
                                    <RefreshCw className="w-5 h-5 text-red-600" />
                                </div>
                                <div>
                                    <h3 className="font-medium text-gray-900">Réinitialiser les compteurs</h3>
                                    <p className="text-sm text-gray-600">Remet à zéro tous les compteurs selon les règles</p>
                                </div>
                            </button>

                            <button
                                onClick={openManualResetPage}
                                className="flex items-center gap-3 p-4 border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors text-left"
                            >
                                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <Settings className="w-5 h-5 text-blue-600" />
                                </div>
                                <div>
                                    <h3 className="font-medium text-gray-900">Interface d'administration</h3>
                                    <p className="text-sm text-gray-600">Ouvre l'interface complète d'administration</p>
                                </div>
                            </button>
                        </div>
                    </div>
                )}

                {/* Stats Cards */}
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 lg:gap-6 mb-8">
                    <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs lg:text-sm font-medium text-gray-600">CP restants</p>
                                <p className="text-xl lg:text-2xl font-bold text-gray-900">{leaveCounters.availableCP}</p>
                                <p className="text-xs text-gray-500">jours</p>
                            </div>
                            <div className="w-8 h-8 lg:w-12 lg:h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                <CalendarIcon className="w-4 h-4 lg:w-6 lg:h-6 text-blue-600" />
                            </div>
                        </div>
                    </div>

                    <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs lg:text-sm font-medium text-gray-600">RTT restants</p>
                                <p className="text-xl lg:text-2xl font-bold text-gray-900">{leaveCounters.availableRTT}</p>
                                <p className="text-xs text-gray-500">jours</p>
                            </div>
                            <div className="w-8 h-8 lg:w-12 lg:h-12 bg-green-100 rounded-lg flex items-center justify-center">
                                <Clock className="w-4 h-4 lg:w-6 lg:h-6 text-green-600" />
                            </div>
                        </div>
                    </div>

                    <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs lg:text-sm font-medium text-gray-600">RTT en cours</p>
                                <p className="text-xl lg:text-2xl font-bold text-gray-900">{leaveCounters.rttInProcess}</p>
                                <p className="text-xs text-gray-500">en cours</p>
                            </div>
                            <div className="w-8 h-8 lg:w-12 lg:h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                                <Users className="w-4 h-4 lg:w-6 lg:h-6 text-yellow-600" />
                            </div>
                        </div>
                    </div>

                    <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-xs lg:text-sm font-medium text-gray-600">Absences</p>
                                <p className="text-xl lg:text-2xl font-bold text-gray-900">{leaveCounters.absenteism}</p>
                                <p className="text-xs text-gray-500">jours</p>
                            </div>
                            <div className="w-8 h-8 lg:w-12 lg:h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                                <TrendingUp className="w-4 h-4 lg:w-6 lg:h-6 text-purple-600" />
                            </div>
                        </div>
                    </div>
                </div>

                {/* Filtres et Recherche */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 lg:p-6 mb-6">
                    <div className="flex flex-col lg:flex-row gap-4">
                        {/* Barre de recherche */}
                        <div className="flex-1">
                            <div className="relative">
                                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                                <input
                                    type="text"
                                    placeholder="Rechercher par type, motif ou date..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                                />
                            </div>
                        </div>

                        {/* Filtres */}
                        <div className="flex gap-3">
                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                            >
                                <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>
                            </select>

                            <select
                                value={typeFilter}
                                onChange={(e) => setTypeFilter(e.target.value)}
                                className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                            >
                                <option value="all">Tous les types</option>
                                <option value="Congés payés">Congés payés</option>
                                <option value="RTT">RTT</option>
                                <option value="Congé maladie">Congé maladie</option>
                                <option value="Autres">Autres types de congés</option> {/* Nouvelle option */}
                            </select>
                        </div>
                    </div>

                    {/* Statistiques des résultats */}
                    <div className="mt-4 text-sm text-gray-600">
                        {filteredRequests.length} demande{filteredRequests.length > 1 ? 's' : ''} trouvée{filteredRequests.length > 1 ? 's' : ''}
                        {allRequests.length !== filteredRequests.length && ` sur ${allRequests.length} au total`}
                    </div>
                </div>

                {/* Liste des Demandes */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100">
                    <div className="p-6 border-b border-gray-100">
                        <div className="flex items-center justify-between">
                            <h2 className="text-xl font-semibold text-gray-900">
                                Toutes mes demandes
                            </h2>
                            <div className="flex items-center gap-2 text-sm text-gray-500">
                                <Filter className="w-4 h-4" />
                                Page {currentPage} sur {totalPages || 1}
                            </div>
                        </div>
                    </div>

                    <div className="p-6">
                        {currentRequests.length === 0 ? (
                            <div className="text-center py-8">
                                <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
                                    <CalendarIcon className="w-6 h-6 text-gray-400" />
                                </div>
                                <p className="text-gray-600 mb-4">
                                    {filteredRequests.length === 0 && allRequests.length > 0
                                        ? 'Aucune demande ne correspond à vos critères'
                                        : 'Aucune demande trouvée'
                                    }
                                </p>
                                <button
                                    onClick={() => setShowNewRequestModal(true)}
                                    className="text-blue-600 hover:text-blue-800 text-sm font-medium"
                                >
                                    {allRequests.length === 0 ? 'Faire votre première demande' : 'Créer une nouvelle demande'}
                                </button>
                            </div>
                        ) : (
                            <>
                                {/* Version Desktop */}
                                <div className="hidden lg:block">
                                    <div className="overflow-x-auto">
                                        <table className="w-full">
                                            <thead>
                                                <tr className="border-b border-gray-200">
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Type</th>
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Dates</th>
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Durée</th>
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Statut</th>
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Soumis le</th>
                                                    <th className="text-left py-3 px-4 font-medium text-gray-700">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {currentRequests.map((request) => (
                                                    <tr key={request.id} className="border-b border-gray-100 hover:bg-gray-50">
                                                        <td className="py-4 px-4">
                                                            <span className="font-medium text-gray-900">{request.type}</span>
                                                        </td>
                                                        <td className="py-4 px-4 text-gray-600">{request.dateDisplay}</td>
                                                        <td className="py-4 px-4 text-gray-600">{request.days} jour{request.days > 1 ? 's' : ''}</td>
                                                        <td className="py-4 px-4">
                                                            <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(request.status)}`}>
                                                                {request.status}
                                                            </span>
                                                        </td>
                                                        <td className="py-4 px-4 text-gray-600">{request.submittedDisplay}</td>
                                                        <td className="py-4 px-4">
                                                            <div className="flex items-center gap-2">
                                                                <button
                                                                    onClick={() => handleViewRequest(request)}
                                                                    className="p-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded"
                                                                    title="Voir les détails"
                                                                >
                                                                    <Eye className="w-4 h-4" />
                                                                </button>
                                                                {request.status === 'En attente' && (
                                                                    <>
                                                                        <button
                                                                            onClick={() => handleEditRequest(request)}
                                                                            className="p-1 text-green-600 hover:text-green-800 hover:bg-green-50 rounded"
                                                                            title="Modifier"
                                                                        >
                                                                            <Edit className="w-4 h-4" />
                                                                        </button>
                                                                        <button
                                                                            onClick={() => handleDeleteRequest(request)}
                                                                            className="p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded"
                                                                            title="Supprimer"
                                                                        >
                                                                            <Trash2 className="w-4 h-4" />
                                                                        </button>
                                                                    </>
                                                                )}
                                                            </div>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

                                {/* Version Mobile */}
                                <div className="lg:hidden space-y-4">
                                    {currentRequests.map((request) => (
                                        <div key={request.id} className="border border-gray-200 rounded-lg p-4">
                                            <div className="flex items-start justify-between mb-3">
                                                <div>
                                                    <h3 className="font-medium text-gray-900">{request.type}</h3>
                                                    <p className="text-sm text-gray-600">{request.dateDisplay}</p>
                                                </div>
                                                <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(request.status)}`}>
                                                    {request.status}
                                                </span>
                                            </div>

                                            <div className="flex items-center justify-between text-sm text-gray-600 mb-3">
                                                <span>{request.days} jour{request.days > 1 ? 's' : ''}</span>
                                                <span>Soumis le {request.submittedDisplay}</span>
                                            </div>

                                            {request.reason && request.reason !== 'Aucun commentaire' && (
                                                <p className="text-sm text-gray-600 mb-3 italic">"{request.reason}"</p>
                                            )}

                                            <div className="flex items-center gap-3 pt-3 border-t border-gray-100">
                                                <button
                                                    onClick={() => handleViewRequest(request)}
                                                    className="flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm"
                                                >
                                                    <Eye className="w-4 h-4" />
                                                    Voir
                                                </button>
                                                {request.status === 'En attente' && (
                                                    <>
                                                        <button
                                                            onClick={() => handleEditRequest(request)}
                                                            className="flex items-center gap-1 text-green-600 hover:text-green-800 text-sm"
                                                        >
                                                            <Edit className="w-4 h-4" />
                                                            Modifier
                                                        </button>
                                                        <button
                                                            onClick={() => handleDeleteRequest(request)}
                                                            className="flex items-center gap-1 text-red-600 hover:text-red-800 text-sm"
                                                        >
                                                            <Trash2 className="w-4 h-4" />
                                                            Supprimer
                                                        </button>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    ))}
                                </div>

                                {/* Pagination */}
                                {totalPages > 1 && (
                                    <div className="flex items-center justify-between mt-6 pt-6 border-t border-gray-100">
                                        <div className="text-sm text-gray-600">
                                            Affichage de {indexOfFirstRequest + 1} à {Math.min(indexOfLastRequest, filteredRequests.length)} sur {filteredRequests.length} demandes
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <button
                                                onClick={() => paginate(currentPage - 1)}
                                                disabled={currentPage === 1}
                                                className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                                            >
                                                Précédent
                                            </button>

                                            {[...Array(totalPages)].map((_, index) => {
                                                const pageNumber = index + 1;
                                                if (
                                                    pageNumber === 1 ||
                                                    pageNumber === totalPages ||
                                                    (pageNumber >= currentPage - 1 && pageNumber <= currentPage + 1)
                                                ) {
                                                    return (
                                                        <button
                                                            key={pageNumber}
                                                            onClick={() => paginate(pageNumber)}
                                                            className={`px-3 py-1 border rounded text-sm ${currentPage === pageNumber
                                                                    ? 'bg-blue-600 text-white border-blue-600'
                                                                    : 'border-gray-300 hover:bg-gray-50'
                                                                }`}
                                                        >
                                                            {pageNumber}
                                                        </button>
                                                    );
                                                } else if (
                                                    pageNumber === currentPage - 2 ||
                                                    pageNumber === currentPage + 2
                                                ) {
                                                    return <span key={pageNumber} className="px-2 text-gray-400">...</span>;
                                                }
                                                return null;
                                            })}

                                            <button
                                                onClick={() => paginate(currentPage + 1)}
                                                disabled={currentPage === totalPages}
                                                className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
                                            >
                                                Suivant
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </div>

                {/* Modal nouvelle demande */}
                {showNewRequestModal && (
                    <NewLeaveRequestModal
                        onClose={() => setShowNewRequestModal(false)}
                        availableLeaveCounters={leaveCounters}
                        userId={user?.id}
                        onRequestSubmitted={() => {
                            fetchLeaveCounters();
                            fetchAllRequests();
                        }}
                    />
                )}
            </div>
        </div>
    );
};

export default Requests;