const { useState, useMemo } = React;

window.AdminVacaciones = function({ globalUsers = [], vacations = [], settings = {}, updateVacationRate, setVacationStatus, revokeEntireVacation, setSelectedUserVacation }) {
    const [vacPage, setVacPage] = useState(0); 
    const [vacRateLocal, setVacRateLocal] = useState(settings?.vacationRate || 2.5);

    const approvedVacsHistory = useMemo(() => {
        return (vacations || [])
            .filter(v => v.status === 'approved')
            .sort((a,b) => (b.requestedAt || 0) - (a.requestedAt || 0));
    }, [vacations]);

    const totalVacPages = Math.ceil(approvedVacsHistory.length / 5);
    const paginatedVacs = approvedVacsHistory.slice(vacPage * 5, (vacPage + 1) * 5);

    return (
        <div className="grid lg:grid-cols-3 gap-6 fade-in">
            {/* CONFIGURACIÓN DE TASA */}
            <div className="bg-white p-8 rounded-[3rem] shadow-sm space-y-4 h-fit border-t-[12px] border-emerald-500">
                <h3 className="font-black text-lg text-slate-900">Reglas Vacacionales</h3>
                <p className="text-[11px] text-slate-500 font-medium leading-relaxed">
                    Tasa maestra de acumulación mensual por cada 30 días naturales trabajados (Ley Laboral NI).
                </p>
                <input 
                    type="number" 
                    step="0.1" 
                    value={vacRateLocal} 
                    onChange={e => setVacRateLocal(e.target.value)} 
                    className="w-full p-4 bg-slate-50 rounded-2xl font-bold outline-none focus:ring-2 focus:ring-emerald-100 text-slate-800" 
                />
                <button onClick={() => updateVacationRate(vacRateLocal)} className="w-full py-4 bg-emerald-600 text-white font-black rounded-2xl uppercase tracking-widest text-[10px] shadow-lg active:scale-95 transition-all">
                    Guardar Configuración
                </button>
            </div>
            
            <div className="lg:col-span-2 space-y-10">
                {/* SOLICITUDES ENTRANTES */}
                <div>
                    <h3 className="font-black text-sm uppercase tracking-widest text-slate-800 border-b border-slate-200 pb-3 mb-6">Solicitudes Entrantes</h3>
                    {vacations.filter(v => v.status === 'pending').length === 0 ? (
                        <div className="bg-white rounded-[2.5rem] p-8 text-center border border-slate-100 shadow-sm"><p className="text-xs font-bold text-slate-400">Bandeja limpia.</p></div>
                    ) : (
                        vacations.filter(v => v.status === 'pending').map(v => (
                            <div key={v.id} className="bg-yellow-50 p-6 rounded-[2.5rem] flex flex-col md:flex-row justify-between items-center shadow-sm gap-4 border border-yellow-200 mb-4">
                                <div className="text-center md:text-left">
                                    <h4 className="font-black text-slate-900 text-base">{v.userName}</h4>
                                    <p className="text-[10px] text-yellow-800 font-black uppercase tracking-widest mt-1 bg-yellow-200 px-2 py-1 rounded inline-block">
                                        Pide: {v.type === 'half' ? 'MEDIO DÍA (0.5)' : `${window.getDaysDiff(v.startDate, v.endDate || v.startDate)} DÍA(S)`}
                                    </p>
                                    <p className="text-[10px] text-slate-600 font-bold uppercase mt-2">
                                        Del {window.formatDateToNIC(v.startDate)} {v.type === 'range' ? `al ${window.formatDateToNIC(v.endDate)}` : ''}
                                    </p>
                                </div>
                                <div className="flex gap-2">
                                    <button onClick={() => setVacationStatus(v.id, 'approved')} className="px-6 py-4 bg-emerald-500 text-white rounded-2xl font-black uppercase text-[10px] shadow-lg active:scale-95 transition-all">Aprobar</button>
                                    <button onClick={() => setVacationStatus(v.id, 'denied')} className="px-6 py-4 bg-white text-red-600 rounded-2xl font-black uppercase text-[10px] active:scale-95 transition-all border border-red-200">Denegar</button>
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* TABLA DE SALDOS */}
                <div>
                    <div className="flex items-center justify-between border-b border-slate-200 pb-3 mb-6">
                        <h3 className="font-black text-sm uppercase tracking-widest text-slate-800">Saldos</h3>
                        <span className="text-[9px] text-slate-400 bg-slate-100 px-3 py-1.5 rounded-full font-black tracking-widest">TOCA EL NOMBRE PARA GESTIONAR</span>
                    </div>
                    <div className="bg-white rounded-[3rem] shadow-sm overflow-hidden border border-slate-100">
                        <table className="w-full text-left">
                            <thead className="bg-slate-50 text-[9px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-100">
                                <tr>
                                    <th className="p-6">Consultor (Perfil)</th>
                                    <th className="p-6 text-center">Disponible</th>
                                    <th className="p-6">Contrato</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-50">
                                {globalUsers.map(u => (
                                    <tr key={u.id} className="hover:bg-slate-50/50 transition-colors cursor-pointer group" onClick={() => setSelectedUserVacation(u)}>
                                        <td className="p-6 font-black text-slate-800 text-xs">{u.name}</td>
                                        <td className="p-6 font-black text-emerald-600 text-lg text-center">
                                            {window.calculateVacationBalance(u, settings?.vacationRate || 2.5, vacations)}
                                        </td>
                                        <td className="p-6 font-bold text-[10px] text-slate-400">
                                            {window.formatDateToNIC(u.hiringDate)}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>

                {/* HISTORIAL Y REVOCACIÓN DE VACACIONES APROBADAS */}
                <div>
                    <div className="flex justify-between items-center border-b border-slate-200 pb-3 mb-6">
                        <h3 className="font-black text-sm uppercase tracking-widest text-slate-800">Aprobadas General</h3>
                        <div className="flex gap-2 items-center bg-white rounded-full shadow-sm border border-slate-200 px-2 py-1">
                            <button disabled={vacPage===0} onClick={()=>setVacPage(p=>p-1)} className={`p-2 rounded-full transition-colors ${vacPage===0?'opacity-30':'hover:bg-slate-100 text-slate-600'}`}><svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7"></path></svg></button>
                            <span className="text-[10px] font-black text-slate-400 px-3 tracking-widest">{vacPage+1} / {totalVacPages||1}</span>
                            <button disabled={vacPage>=(totalVacPages-1)} onClick={()=>setVacPage(p=>p+1)} className={`p-2 rounded-full transition-colors ${vacPage>=(totalVacPages-1)?'opacity-30':'hover:bg-slate-100 text-slate-600'}`}><svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"></path></svg></button>
                        </div>
                    </div>

                    {paginatedVacs.length === 0 ? (
                        <p className="text-xs font-bold text-slate-400">Sin registros históricos.</p>
                    ) : (
                        paginatedVacs.map(v => {
                            const daysCount = v.type === 'half' ? 0.5 : (v.type === 'paid' ? v.paidDays : window.getDaysDiff(v.startDate, v.endDate || v.startDate));

                            return (
                                <div key={v.id} className="bg-white p-6 rounded-[2.5rem] border border-slate-100 shadow-sm flex flex-col md:flex-row justify-between items-center mb-4 transition-all hover:border-indigo-100">
                                    <div className="text-center md:text-left">
                                        <div className="flex items-center gap-2">
                                            <h4 className="font-black text-slate-900 text-sm">{v.userName}</h4>
                                            <span className="px-2 py-0.5 bg-emerald-50 text-emerald-700 text-[9px] font-black rounded-lg border border-emerald-200 uppercase">
                                                {daysCount} DÍA(S)
                                            </span>
                                        </div>
                                        <p className="text-[10px] text-slate-500 font-bold uppercase mt-1 tracking-widest">
                                            {v.type === 'paid' ? `PAGO EN EFECTIVO (${v.paidDays} DÍAS)` : `DEL ${window.formatDateToNIC(v.startDate)} ${v.type === 'range' ? `AL ${window.formatDateToNIC(v.endDate)}` : ''}`}
                                        </p>
                                        {v.notes && <p className="text-[10px] text-slate-400 italic mt-1">"{v.notes}"</p>}
                                    </div>

                                    {/* BOTÓN PARA REVOCAR Y REINTEGRAR DÍAS */}
                                    <button 
                                        onClick={() => revokeEntireVacation(v)} 
                                        className="mt-3 md:mt-0 px-4 py-2.5 bg-red-50 text-red-600 hover:bg-red-600 hover:text-white rounded-xl font-black uppercase text-[9px] tracking-wider transition-all active:scale-95 border border-red-100"
                                    >
                                        Revocar Vacación
                                    </button>
                                </div>
                            );
                        })
                    )}
                </div>
            </div>
        </div>
    );
};