import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import Sidebar from '../components/Sidebar';
import { Calendar, Clock, CheckCircle, XCircle } from 'lucide-react';

const EmployeeDetails = () => {
    const { id } = useParams();
    const [employee, setEmployee] = useState(null);
    const [requests, setRequests] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        fetchEmployeeData();
    }, [id]);

    const fetchEmployeeData = async () => {
        try {
            setIsLoading(true);

            // 1️⃣ Données employé
            const resEmployee = await fetch(`http://localhost/GTA/project/public/php/getEmploye.php?id=${id}`);
            const dataEmployee = await resEmployee.json();

            if (!dataEmployee.success) {
                setEmployee(null);
                return;
            }
            setEmployee(dataEmployee.employee);

            // 2️⃣ Historique des demandes
            const resRequests = await fetch(`http://localhost/GTA/project/public/php/getEmployeRequest.php?id=${id}`);
            const dataRequests = await resRequests.json();
            setRequests(dataRequests.requests || []);

            // 3️⃣ Compteurs de congés et RTT
            const resCounters = await fetch(`http://localhost/GTA/project/public/php/getLeaveCounters.php?user_id=${id}`);
            const dataCounters = await resCounters.json();

            if (dataCounters.success) {
                setEmployee(prev => ({
                    ...prev,
                    conges_restants: dataCounters.counters.availableCP,
                    rtt_restants: dataCounters.counters.availableRTT
                }));
            }

        } catch (err) {
            console.error("Erreur récupération données collaborateur:", err);
        } finally {
            setIsLoading(false);
        }
    };

    const getStatusIcon = (status) => {
        switch (status) {
            case 'Validée':
                return <CheckCircle className="inline text-green-500 mr-1" />;
            case 'Refusée':
            case 'Annulée':
                return <XCircle className="inline text-red-500 mr-1" />;
            default:
                return <Clock className="inline text-yellow-500 mr-1" />;
        }
    };

    if (isLoading) return <p className="text-center p-6">Chargement...</p>;
    if (!employee) return <p className="text-center p-6">Collaborateur introuvable</p>;

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

            <div className="flex-1 lg:ml-60 p-6">
                <h1 className="text-2xl font-bold mb-2">{employee.Prenom} {employee.Nom}</h1>
                <p className="text-gray-600 mb-6">{employee.Email}</p>

                {/* Compteurs congés/RTT */}
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
                    <div className="bg-white p-4 rounded-xl shadow">
                        <p className="text-sm text-gray-600">Congés restants</p>
                        <p className="text-xl font-bold">{employee.conges_restants || 0} jours</p>
                    </div>
                    <div className="bg-white p-4 rounded-xl shadow">
                        <p className="text-sm text-gray-600">RTT restants</p>
                        <p className="text-xl font-bold">{employee.rtt_restants || 0} jours</p>
                    </div>
                </div>

                {/* Historique des congés */}
                <h2 className="text-lg font-semibold mb-4">Historique des congés</h2>
                <div className="space-y-3">
                    {requests.length === 0 ? (
                        <p className="text-gray-500">Aucune demande</p>
                    ) : (
                        requests.map((r) => (
                            <div key={r.Id} className="bg-white p-4 rounded-xl shadow border flex justify-between items-center">
                                <div>
                                    <p className="font-medium">{r.type} - {r.days}j</p>
                                    <p className="text-sm text-gray-600">{r.date_display}</p>
                                </div>
                                <div className="flex items-center">
                                    {getStatusIcon(r.status)}
                                    <span className="text-sm text-gray-700">{r.status}</span>
                                </div>
                            </div>
                        ))
                    )}
                </div>
            </div>
        </div>
    );
};

export default EmployeeDetails;
