import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import Sidebar from '../components/Sidebar';
import { Plus, Search, Filter, Eye, Menu, X } from 'lucide-react';
import NewLeaveRequestModal from '../components/NewLeaveRequestModal';
import { useMsal } from "@azure/msal-react";   

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 [isLoading, setIsLoading] = useState(true);

    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;

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

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

    useEffect(() => {
        if (userId) {
            fetchLeaveCounters();
            fetchAllRequests();
        }
    }, [user]);

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

        if (searchTerm) {
            filtered = filtered.filter(request =>
                request.type.toLowerCase().includes(searchTerm.toLowerCase()) ||
                request.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
                request.dateDisplay.includes(searchTerm)
            );
        }

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

        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);
    }, [allRequests, searchTerm, statusFilter, typeFilter]);

    const fetchLeaveCounters = async () => {
        try {
            const response = await fetch(`http://localhost/GTA/project/public/php/getLeaveCounters.php?user_id=${userId}`);
            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) {
                setLeaveCounters(data.counters);
            } else {
                throw new Error(data.message || 'Erreur lors de la récupération des compteurs');
            }
        } catch (error) {
            console.error('Erreur compteurs:', error);
        }
    };

    const fetchAllRequests = async () => {
        try {
            const url = `http://localhost/GTA/project/public/php/getRequests.php?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) {
                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);
        } finally {
            setIsLoading(false);
        }
    };

    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é':
            case 'Refusée': return 'bg-red-100 text-red-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    };

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

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

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

    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 top bar */}
                <div className="lg:hidden flex justify-between items-center 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 className="flex items-center gap-2">
                        <button onClick={() => setShowFilters(!showFilters)} className="p-2 rounded-lg bg-white shadow-sm border border-gray-200 flex items-center gap-2">
                            <Filter className="w-4 h-4" /> <span className="text-sm">Filtres</span>
                        </button>
                        <button onClick={() => setShowNewRequestModal(true)} className="p-2 rounded-lg bg-blue-600 text-white">
                            <Plus className="w-4 h-4" />
                        </button>
                    </div>
                </div>

                {/* Header */}
                <div className="flex justify-between items-center mb-4 lg:mb-8">
                    <div>
                        <h1 className="text-2xl lg:text-3xl font-bold text-gray-900 mb-1">Mes Demandes de Congés</h1>
                        <p className="text-sm text-gray-600">Gérez toutes vos demandes de congés</p>
                    </div>

                    <div className="hidden lg:flex items-center gap-3">
                        <button onClick={() => setShowNewRequestModal(true)} className="bg-cyan-600 text-white px-4 py-2 rounded-lg flex items-center gap-2">
                            <Plus className="w-4 h-4" /> Nouvelle demande
                        </button>
                    </div>
                </div>

                {/* Filters panel (mobile toggle + desktop always visible) */}
                <div className={`${showFilters ? 'block' : 'hidden'} lg:block 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">
                        <div className="flex-1 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 text-sm"
                            />
                        </div>

                        <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg 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 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</option>
                        </select>
                    </div>

                    <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>

                {/* Main content: left = list/table, right = details (desktop) */}
                <div className="flex flex-col lg:flex-row gap-6">
                    {/* Left: table (desktop) + cards (mobile) */}
                    <div className="flex-1 bg-white rounded-xl shadow-sm border border-gray-100">
                        <div className="p-6 border-b border-gray-100 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" />
                                <span>Page {currentPage} / {totalPages || 1}</span>
                            </div>
                        </div>

                        <div className="p-6">
                            {currentRequests.length === 0 ? (
                                <div className="text-center py-8 text-gray-600">Aucune demande à afficher.</div>
                            ) : (
                                <>
                                    {/* Desktop table */}
                                    <div className="hidden lg:block overflow-x-auto">
                                        <table className="w-full">
                                            <thead>
                                                <tr className="border-b border-gray-200">
                                                    <th className="text-left py-3 px-4 text-gray-700">Type</th>
                                                    <th className="text-left py-3 px-4 text-gray-700">Dates</th>
                                                    <th className="text-left py-3 px-4 text-gray-700">Jours</th>
                                                    <th className="text-left py-3 px-4 text-gray-700">Statut</th>
                                                    <th className="text-left py-3 px-4 text-gray-700">Soumis</th>
                                                    <th className="text-left py-3 px-4 text-gray-700">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {currentRequests.map(request => (
                                                    <tr key={request.id} className="border-b hover:bg-gray-50">
                                                        <td className="py-4 px-4">
                                                            {request.type.split(',').map((t, i) => (
                                                                <span key={i} className="inline-block bg-gray-100 text-gray-800 text-[11px] px-2 py-0.5 rounded-full mr-1">
                                                                    {t.trim()}
                                                                </span>
                                                            ))}
                                                        </td>
                                                        <td className="py-4 px-4">{request.dateDisplay}</td>
                                                        <td className="py-4 px-4">{request.days}</td>
                                                        <td className="py-4 px-4">
                                                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${getStatusColor(request.status)}`}>
                                                                {request.status}
                                                            </span>
                                                        </td>
                                                        <td className="py-4 px-4">{request.submittedDisplay}</td>
                                                        <td className="py-4 px-4">
                                                            <button onClick={() => handleViewRequest(request)} className="text-blue-600 hover:underline text-sm flex items-center gap-1">
                                                                <Eye className="w-4 h-4" /> Voir
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>

                                    {/* Mobile cards */}
                                    <div className="lg:hidden space-y-4">
                                        {currentRequests.map(request => (
                                            <div key={request.id} className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
                                                <div className="flex justify-between items-start">
                                                    <div className="flex-1">
                                                        <div className="flex flex-wrap gap-1 mb-2">
                                                            {request.type.split(',').map((t, i) => (
                                                                <span key={i} className="bg-gray-100 text-gray-800 text-[11px] px-2 py-0.5 rounded-full">
                                                                    {t.trim()}
                                                                </span>
                                                            ))}
                                                        </div>
                                                        <p className="text-sm text-gray-600">{request.dateDisplay}</p>
                                                        <p className="text-sm font-medium mt-1">{request.days} jour{request.days > 1 ? 's' : ''}</p>
                                                    </div>
                                                    <div className="ml-3">
                                                        <span className={`px-2 py-0.5 rounded-full text-[10px] font-medium ${getStatusColor(request.status)}`}>
                                                            {request.status}
                                                        </span>
                                                    </div>
                                                </div>

                                                <div className="mt-3 flex justify-between items-center text-sm">
                                                    <span className="text-gray-500">{request.submittedDisplay}</span>
                                                    <button onClick={() => handleViewRequest(request)} className="text-blue-600 flex items-center gap-1">
                                                        <Eye className="w-4 h-4" /> Voir
                                                    </button>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </>
                            )}
                        </div>
                    </div>

                    {/* Right: details (desktop) */}
                    <div className="hidden lg:block w-full lg:max-w-sm">
                        {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.fileUrl && (
                                        <div>
                                            <p className="text-gray-500">Arrêt maladie</p>
                                            <a href={selectedRequest.fileUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline flex items-center gap-2">
                                                <Eye className="w-4 h-4" /> Voir le fichier
                                            </a>
                                        </div>
                                    )}
                                </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>

                {/* Mobile details modal */}
                {selectedRequest && (
                    <div className="fixed inset-0 z-50 lg:hidden">
                        <div className="absolute inset-0 bg-black bg-opacity-40" onClick={handleCloseDetails}></div>
                        <div className="absolute inset-0 flex items-center justify-center p-4">
                            <div className="bg-white w-full max-w-md h-full overflow-y-auto rounded-lg p-5">
                                <div className="flex justify-between items-center mb-4">
                                    <h3 className="text-lg font-semibold">Détails</h3>
                                    <button onClick={handleCloseDetails} className="text-gray-500">
                                        <X className="w-6 h-6" />
                                    </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.fileUrl && (
                                        <div>
                                            <p className="text-gray-500">Arrêt maladie</p>
                                            <a href={selectedRequest.fileUrl} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline flex items-center gap-2">
                                                <Eye className="w-4 h-4" /> Voir le fichier
                                            </a>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* New request modal */}
                {showNewRequestModal && (
                    <NewLeaveRequestModal
                        onClose={() => setShowNewRequestModal(false)}
                        availableLeaveCounters={leaveCounters}
                        userId={user?.id}
                        userEmail={user.email}
                        userName={`${user.prenom} ${user.nom}`}
                        onRequestSubmitted={() => {
                            fetchLeaveCounters();
                            fetchAllRequests();
                        }}
                    />
                )}
            </div>
        </div>
    );
};

export default Requests;
