import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import Sidebar from '../components/Sidebar';
import {
    Calendar,
    Clock,
    CheckCircle,
    XCircle,
    ArrowLeft,
    Mail,
    Briefcase,
    Building,
    TrendingDown,
    TrendingUp,
    ChevronLeft,
    ChevronRight,
    FileText,
    AlertCircle
} from 'lucide-react';

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

    // États pour le CRA
    const [craData, setCraData] = useState(null);
    const [craMonth, setCraMonth] = useState(new Date().getMonth() + 1);
    const [craYear, setCraYear] = useState(new Date().getFullYear());
    const [isLoadingCra, setIsLoadingCra] = useState(false);

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

    useEffect(() => {
        if (employee && detailedCounters?.user?.typeContrat === 'forfait_jour') {
            fetchCraData();
        }
    }, [id, craMonth, craYear, employee, detailedCounters]);

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

            const resEmployee = await fetch(`/api/getEmploye?id=${id}`);
            const dataEmployee = await resEmployee.json();

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

            setEmployee(dataEmployee.employee);

            const resCounters = await fetch(`/api/getDetailedLeaveCounters?user_id=${id}`);
            const dataCounters = await resCounters.json();

            if (dataCounters.success) {
                setDetailedCounters(dataCounters.data);
            }

            const resRequests = await fetch(`/api/getEmployeRequest?id=${id}`);
            const dataRequests = await resRequests.json();

            if (dataRequests.success) {
                setRequests(dataRequests.requests || []);
            }

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

    const fetchCraData = async () => {
        try {
            setIsLoadingCra(true);
            const res = await fetch(`/api/getCra?user_id=${id}&month=${craMonth}&year=${craYear}`);
            const data = await res.json();

            if (data.success) {
                setCraData(data.cra);
            } else {
                setCraData(null);
            }
        } catch (err) {
            console.error("Erreur récupération CRA:", err);
            setCraData(null);
        } finally {
            setIsLoadingCra(false);
        }
    };

    const navigateCraMonth = (direction) => {
        if (direction === 'prev') {
            if (craMonth === 1) {
                setCraMonth(12);
                setCraYear(craYear - 1);
            } else {
                setCraMonth(craMonth - 1);
            }
        } else {
            if (craMonth === 12) {
                setCraMonth(1);
                setCraYear(craYear + 1);
            } else {
                setCraMonth(craMonth + 1);
            }
        }
    };

    const getMonthName = (month) => {
        const months = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
            'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
        return months[month - 1];
    };

    const getDaysInMonth = (month, year) => {
        return new Date(year, month, 0).getDate();
    };

    const getFirstDayOfMonth = (month, year) => {
        const day = new Date(year, month - 1, 1).getDay();
        return day === 0 ? 6 : day - 1;
    };

    const isWeekend = (day, month, year) => {
        const date = new Date(year, month - 1, day);
        const dayOfWeek = date.getDay();
        return dayOfWeek === 0 || dayOfWeek === 6;
    };

    const getCraDayStatus = (day) => {
        if (!craData || !craData.days) return null;
        return craData.days.find(d => d.day === day);
    };

    const getCraDayClass = (dayStatus, isWeekendDay) => {
        if (isWeekendDay) return 'bg-gray-100 text-gray-400';
        if (!dayStatus) return 'bg-white text-gray-700';

        switch (dayStatus.type) {
            case 'worked':
                return 'bg-emerald-100 text-emerald-700 border border-emerald-300';
            case 'leave':
                return 'bg-blue-100 text-blue-700 border border-blue-300';
            case 'rtt':
                return 'bg-violet-100 text-violet-700 border border-violet-300';
            case 'sick':
                return 'bg-red-100 text-red-700 border border-red-300';
            case 'holiday':
                return 'bg-amber-100 text-amber-700 border border-amber-300';
            case 'not_worked':
                return 'bg-orange-100 text-orange-700 border border-orange-300';
            case 'missing':
                return 'bg-red-200 text-red-800 border-2 border-red-400';
            case 'pending':
                return 'bg-gray-50 text-gray-400 border border-dashed border-gray-300';
            default:
                return 'bg-white text-gray-700 border border-gray-200';
        }
    };

    // ✅ NOUVELLE FONCTION : Formatage des dates côté frontend
    const formatDateRange = (start, end) => {
        if (!start) return 'Date non définie';

        const formatDate = (dateStr) => {
            try {
                const date = new Date(dateStr);
                if (isNaN(date.getTime())) return 'Date invalide';
                return date.toLocaleDateString('fr-FR', {
                    day: '2-digit',
                    month: '2-digit',
                    year: 'numeric'
                });
            } catch {
                return 'Date invalide';
            }
        };

        if (start === end) return formatDate(start);
        return `${formatDate(start)} - ${formatDate(end)}`;
    };

    const getStatusConfig = (status) => {
        switch (status) {
            case 'Validée':
                return {
                    icon: <CheckCircle className="w-4 h-4" />,
                    bg: 'bg-emerald-50',
                    text: 'text-emerald-700',
                    dot: 'bg-emerald-500'
                };
            case 'Refusée':
            case 'Annulée':
                return {
                    icon: <XCircle className="w-4 h-4" />,
                    bg: 'bg-red-50',
                    text: 'text-red-700',
                    dot: 'bg-red-500'
                };
            default:
                return {
                    icon: <Clock className="w-4 h-4" />,
                    bg: 'bg-amber-50',
                    text: 'text-amber-700',
                    dot: 'bg-amber-500'
                };
        }
    };

    const getTypeContratLabel = (type) => {
        switch (type) {
            case '37h': return '37h/sem';
            case 'forfait_jour': return 'Forfait jour';
            case 'temps_partiel': return 'Temps partiel';
            default: return type || '37h/sem';
        }
    };

    const CounterCard = ({ label, solde, acquis, pris, color, icon: Icon }) => {
        const colorClasses = {
            blue: { bg: 'bg-blue-500', light: 'bg-blue-50', text: 'text-blue-600', border: 'border-blue-200' },
            cyan: { bg: 'bg-cyan-500', light: 'bg-cyan-50', text: 'text-cyan-600', border: 'border-cyan-200' },
            green: { bg: 'bg-emerald-500', light: 'bg-emerald-50', text: 'text-emerald-600', border: 'border-emerald-200' },
            purple: { bg: 'bg-violet-500', light: 'bg-violet-50', text: 'text-violet-600', border: 'border-violet-200' },
        };

        const c = colorClasses[color] || colorClasses.blue;

        return (
            <div className={`relative bg-white rounded-2xl border ${c.border} p-5 hover:shadow-md transition-shadow`}>
                <div className="flex items-start justify-between mb-4">
                    <div>
                        <p className="text-sm font-medium text-gray-500 mb-1">{label}</p>
                        <p className={`text-3xl font-bold ${c.text}`}>{solde.toFixed(1)}<span className="text-lg ml-1">j</span></p>
                    </div>
                    <div className={`${c.bg} p-2.5 rounded-xl`}>
                        <Icon className="w-5 h-5 text-white" />
                    </div>
                </div>

                <div className="flex items-center gap-4 text-sm">
                    <div className="flex items-center gap-1.5">
                        <TrendingUp className="w-3.5 h-3.5 text-emerald-500" />
                        <span className="text-gray-600">Acquis:</span>
                        <span className="font-semibold text-gray-900">{acquis.toFixed(1)}j</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                        <TrendingDown className="w-3.5 h-3.5 text-red-400" />
                        <span className="text-gray-600">Pris:</span>
                        <span className="font-semibold text-gray-900">{pris.toFixed(1)}j</span>
                    </div>
                </div>
            </div>
        );
    };

    const renderCraCalendar = () => {
        const daysInMonth = getDaysInMonth(craMonth, craYear);
        const firstDay = getFirstDayOfMonth(craMonth, craYear);
        const dayNames = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];

        const cells = [];

        for (let i = 0; i < firstDay; i++) {
            cells.push(<div key={`empty-${i}`} className="h-10"></div>);
        }

        for (let day = 1; day <= daysInMonth; day++) {
            const isWeekendDay = isWeekend(day, craMonth, craYear);
            const dayStatus = getCraDayStatus(day);
            const dayClass = getCraDayClass(dayStatus, isWeekendDay);

            cells.push(
                <div
                    key={day}
                    className={`h-10 flex items-center justify-center rounded-lg text-sm font-medium ${dayClass} transition-colors relative cursor-default`}
                    title={dayStatus?.label || ''}
                >
                    {day}
                    {dayStatus?.type === 'missing' && (
                        <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-red-500 rounded-full animate-pulse"></span>
                    )}
                </div>
            );
        }

        return (
            <div className="grid grid-cols-7 gap-1">
                {dayNames.map(name => (
                    <div key={name} className="h-8 flex items-center justify-center text-xs font-semibold text-gray-500">
                        {name}
                    </div>
                ))}
                {cells}
            </div>
        );
    };

    const getTauxSaisieColor = (taux) => {
        if (taux >= 80) return 'text-emerald-600';
        if (taux >= 50) return 'text-amber-600';
        return 'text-red-600';
    };

    if (isLoading) return (
        <div className="min-h-screen bg-gray-50 flex items-center justify-center">
            <div className="text-center">
                <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-cyan-600 mx-auto mb-3"></div>
                <p className="text-gray-600">Chargement...</p>
            </div>
        </div>
    );

    if (!employee) return (
        <div className="min-h-screen bg-gray-50 flex items-center justify-center">
            <div className="text-center">
                <p className="text-gray-600 mb-4">Collaborateur introuvable</p>
                <button
                    onClick={() => navigate(-1)}
                    className="text-cyan-600 hover:underline"
                >
                    Retour
                </button>
            </div>
        </div>
    );

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

            <div className="flex-1 lg:ml-60 p-6 lg:p-8">
                {/* Bouton retour */}
                <button
                    onClick={() => navigate(-1)}
                    className="flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6 transition-colors"
                >
                    <ArrowLeft className="w-4 h-4" />
                    <span className="text-sm font-medium">Retour</span>
                </button>

                {/* Profil employé */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 mb-6">
                    <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                        <div className="w-16 h-16 bg-gradient-to-br from-cyan-400 to-blue-500 rounded-2xl flex items-center justify-center flex-shrink-0">
                            <span className="text-2xl font-bold text-white">
                                {employee.Prenom?.charAt(0)}{employee.Nom?.charAt(0)}
                            </span>
                        </div>

                        <div className="flex-1">
                            <h1 className="text-xl font-bold text-gray-900 mb-1">
                                {employee.Prenom} {employee.Nom}
                            </h1>

                            <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-gray-600">
                                <div className="flex items-center gap-1.5">
                                    <Mail className="w-4 h-4 text-gray-400" />
                                    <span>{employee.Email}</span>
                                </div>

                                {detailedCounters?.user?.role && (
                                    <div className="flex items-center gap-1.5">
                                        <Briefcase className="w-4 h-4 text-gray-400" />
                                        <span>{detailedCounters.user.role}</span>
                                    </div>
                                )}

                                {detailedCounters?.user?.service && (
                                    <div className="flex items-center gap-1.5">
                                        <Building className="w-4 h-4 text-gray-400" />
                                        <span>{detailedCounters.user.service}</span>
                                    </div>
                                )}
                            </div>
                        </div>

                        {detailedCounters?.user?.typeContrat && (
                            <div className="px-3 py-1.5 bg-gray-100 rounded-lg text-sm font-medium text-gray-700">
                                {getTypeContratLabel(detailedCounters.user.typeContrat)}
                            </div>
                        )}
                    </div>
                </div>

                {/* Compteurs */}
                {detailedCounters && (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        {detailedCounters.cpN1 && (
                            <CounterCard
                                label="CP N-1"
                                solde={detailedCounters.cpN1.solde}
                                acquis={detailedCounters.cpN1.reporte}
                                pris={detailedCounters.cpN1.pris}
                                color="blue"
                                icon={Calendar}
                            />
                        )}

                        {detailedCounters.cpN && (
                            <CounterCard
                                label="CP N"
                                solde={detailedCounters.cpN.solde}
                                acquis={detailedCounters.cpN.acquis}
                                pris={detailedCounters.cpN.pris}
                                color="cyan"
                                icon={Calendar}
                            />
                        )}

                        {detailedCounters.rttN && detailedCounters.user?.role !== 'Apprenti' && (
                            <CounterCard
                                label={`RTT ${detailedCounters.rttN.annee}`}
                                solde={detailedCounters.rttN.solde}
                                acquis={detailedCounters.rttN.acquis}
                                pris={detailedCounters.rttN.pris}
                                color="green"
                                icon={Clock}
                            />
                        )}

                        {detailedCounters.recupN && (
                            <CounterCard
                                label="Récupérations"
                                solde={detailedCounters.recupN.solde}
                                acquis={detailedCounters.recupN.acquis}
                                pris={detailedCounters.recupN.pris}
                                color="purple"
                                icon={Clock}
                            />
                        )}
                    </div>
                )}

                {/* Section CRA - Uniquement pour forfait jour */}
                {detailedCounters?.user?.typeContrat === 'forfait_jour' && (
                    <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden mb-6">
                        <div className="px-6 py-4 border-b border-gray-100">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-3">
                                    <div className="p-2 bg-cyan-50 rounded-lg">
                                        <FileText className="w-5 h-5 text-cyan-600" />
                                    </div>
                                    <div>
                                        <h2 className="text-lg font-semibold text-gray-900">Compte Rendu d'Activité</h2>
                                        <p className="text-sm text-gray-500">Suivi mensuel des activités</p>
                                    </div>
                                </div>

                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => navigateCraMonth('prev')}
                                        className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                    >
                                        <ChevronLeft className="w-5 h-5 text-gray-600" />
                                    </button>
                                    <span className="text-sm font-medium text-gray-900 min-w-[140px] text-center">
                                        {getMonthName(craMonth)} {craYear}
                                    </span>
                                    <button
                                        onClick={() => navigateCraMonth('next')}
                                        className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                                    >
                                        <ChevronRight className="w-5 h-5 text-gray-600" />
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div className="p-6">
                            {isLoadingCra ? (
                                <div className="flex items-center justify-center py-8">
                                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-600"></div>
                                </div>
                            ) : (
                                <>
                                    {/* Alerte si jours non saisis */}
                                    {craData?.summary?.missing > 0 && (
                                        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3">
                                            <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
                                            <p className="text-sm text-red-700">
                                                <span className="font-semibold">{craData.summary.missing} jour{craData.summary.missing > 1 ? 's' : ''}</span> non saisi{craData.summary.missing > 1 ? 's' : ''} ce mois-ci
                                            </p>
                                        </div>
                                    )}

                                    {/* Calendrier */}
                                    {renderCraCalendar()}

                                    {/* Légende */}
                                    <div className="mt-6 pt-4 border-t border-gray-100">
                                        <p className="text-xs font-medium text-gray-500 mb-3">Légende</p>
                                        <div className="flex flex-wrap gap-3">
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-emerald-100 border border-emerald-300"></div>
                                                <span className="text-xs text-gray-600">Travaillé</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-blue-100 border border-blue-300"></div>
                                                <span className="text-xs text-gray-600">Congés</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-violet-100 border border-violet-300"></div>
                                                <span className="text-xs text-gray-600">RTT</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-red-100 border border-red-300"></div>
                                                <span className="text-xs text-gray-600">Maladie</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-amber-100 border border-amber-300"></div>
                                                <span className="text-xs text-gray-600">Férié</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-orange-100 border border-orange-300"></div>
                                                <span className="text-xs text-gray-600">Non travaillé</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-red-200 border-2 border-red-400 relative">
                                                    <span className="absolute -top-0.5 -right-0.5 w-1.5 h-1.5 bg-red-500 rounded-full"></span>
                                                </div>
                                                <span className="text-xs text-gray-600">Non saisi</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-gray-50 border border-dashed border-gray-300"></div>
                                                <span className="text-xs text-gray-600">À saisir</span>
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <div className="w-4 h-4 rounded bg-gray-100"></div>
                                                <span className="text-xs text-gray-600">Weekend</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Résumé du mois */}
                                    {craData?.summary && (
                                        <div className="mt-4 pt-4 border-t border-gray-100">
                                            <p className="text-xs font-medium text-gray-500 mb-3">Résumé du mois</p>
                                            <div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
                                                <div className="text-center p-3 bg-gray-50 rounded-xl">
                                                    <p className="text-2xl font-bold text-emerald-600">{craData.summary.worked || 0}</p>
                                                    <p className="text-xs text-gray-500">Jours travaillés</p>
                                                </div>
                                                <div className="text-center p-3 bg-gray-50 rounded-xl">
                                                    <p className="text-2xl font-bold text-blue-600">{craData.summary.leave || 0}</p>
                                                    <p className="text-xs text-gray-500">Congés</p>
                                                </div>
                                                <div className="text-center p-3 bg-gray-50 rounded-xl">
                                                    <p className="text-2xl font-bold text-violet-600">{craData.summary.rtt || 0}</p>
                                                    <p className="text-xs text-gray-500">RTT</p>
                                                </div>
                                                <div className="text-center p-3 bg-gray-50 rounded-xl">
                                                    <p className="text-2xl font-bold text-red-600">{craData.summary.missing || 0}</p>
                                                    <p className="text-xs text-gray-500">Non saisis</p>
                                                </div>
                                                <div className="text-center p-3 bg-gray-50 rounded-xl">
                                                    <p className={`text-2xl font-bold ${getTauxSaisieColor(craData.summary.tauxSaisie || 0)}`}>
                                                        {craData.summary.tauxSaisie || 0}%
                                                    </p>
                                                    <p className="text-xs text-gray-500">Taux de saisie</p>
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </>
                            )}
                        </div>
                    </div>
                )}

                {/* Historique ✅ CORRIGÉ */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div className="px-6 py-4 border-b border-gray-100">
                        <h2 className="text-lg font-semibold text-gray-900">Historique des demandes</h2>
                        <p className="text-sm text-gray-500">{requests.length} demande{requests.length > 1 ? 's' : ''}</p>
                    </div>

                    <div className="divide-y divide-gray-100">
                        {requests.length === 0 ? (
                            <div className="px-6 py-12 text-center">
                                <Calendar className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                                <p className="text-gray-500">Aucune demande de congés</p>
                            </div>
                        ) : (
                            requests.map((r) => {
                                const statusConfig = getStatusConfig(r.status || r.Statut);

                                return (
                                    <div key={r.Id} className="px-6 py-4 hover:bg-gray-50 transition-colors">
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center gap-4">
                                                <div className={`w-2 h-2 rounded-full ${statusConfig.dot}`}></div>
                                                <div>
                                                    <p className="font-medium text-gray-900">
                                                        {r.type || r.typeConges || 'Congés'}
                                                    </p>
                                                    {/* ✅ UTILISE formatDateRange avec DateDebut/DateFin */}
                                                    <p className="text-sm text-gray-500">
                                                        {formatDateRange(r.DateDebut, r.DateFin)}
                                                    </p>
                                                </div>
                                            </div>

                                            <div className="flex items-center gap-3">
                                                <span className="text-sm font-semibold text-gray-700">
                                                    {r.days || r.NombreJours || 0}j
                                                </span>
                                                <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${statusConfig.bg} ${statusConfig.text}`}>
                                                    {statusConfig.icon}
                                                    {r.status || r.Statut}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default EmployeeDetails;
