'use client';

import { useState, useEffect } from 'react';
import { CalendarOff, Plus, Trash2, Loader2, User, AlertCircle } from 'lucide-react';

export default function AusenciasTab() {
    const [loading, setLoading] = useState(false);
    const [userId, setUserId] = useState('');
    const [tipo, setTipo] = useState('VACACIONES');
    const [fechaInicio, setFechaInicio] = useState('');
    const [fechaFin, setFechaFin] = useState('');
    const [notas, setNotas] = useState('');
    const [errorLocal, setErrorLocal] = useState('');

    const [localAusencias, setLocalAusencias] = useState<any[]>([]);
    const [tecnicos, setTecnicos] = useState<any[]>([]);

    const fetchData = async () => {
        try {
            const [resT, resA] = await Promise.all([
                fetch('/api/users?role=operario'),
                fetch('/api/ausencias')
            ]);
            if (resT.ok) {
                const bodyT = await resT.json();
                if (bodyT.success && bodyT.users) {
                    setTecnicos(bodyT.users);
                } else if (Array.isArray(bodyT)) {
                    setTecnicos(bodyT);
                } else {
                    setTecnicos(bodyT.tecnicos || []);
                }
            }
            if (resA.ok) {
                const bodyA = await resA.json();
                // Sort array latest to oldest locally
                const sorted = (bodyA || []).sort((a: any, b: any) => new Date(b.fechaInicio).getTime() - new Date(a.fechaInicio).getTime());
                setLocalAusencias(sorted);
            }
        } catch (e) {
            console.error(e);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!userId || !tipo || !fechaInicio || !fechaFin) {
            setErrorLocal('Todos los campos obligatorios deben estar rellenos');
            return;
        }
        setErrorLocal('');
        setLoading(true);

        try {
            const res = await fetch('/api/ausencias', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ userId, tipo, fechaInicio, fechaFin, notas })
            });
            if (!res.ok) {
                const d = await res.json();
                throw new Error(d.error || 'Error creando ausencia');
            }
            // Reset form
            setUserId('');
            setFechaInicio('');
            setFechaFin('');
            setNotas('');
            await fetchData();
        } catch (err: any) {
            setErrorLocal(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!confirm('¿Estás seguro de que quieres eliminar este período de ausencia? Esto volverá a mostrar al técnico como disponible en la Agenda.')) return;

        setLoading(true);
        try {
            const res = await fetch(`/api/ausencias?id=${id}`, {
                method: 'DELETE'
            });
            if (!res.ok) throw new Error('Error al borrar');
            await fetchData();
        } catch (err) {
            console.error(err);
            alert('Hubo un error borrando el registro.');
        } finally {
            setLoading(false);
        }
    };

    const getTipoLabel = (t: string) => {
        if (t === 'VACACIONES') return 'Vacaciones';
        if (t === 'BAJA_MEDICA') return 'Baja Médica';
        return 'Asuntos Propios';
    };

    const getTipoColor = (t: string) => {
        if (t === 'VACACIONES') return 'bg-amber-100 text-amber-800 border-amber-200';
        if (t === 'BAJA_MEDICA') return 'bg-red-100 text-red-800 border-red-200';
        return 'bg-blue-100 text-blue-800 border-blue-200';
    };

    return (
        <div className="space-y-6">

            <div className="flex items-center gap-3 border-b border-gray-100 pb-4">
                <div className="p-3 bg-indigo-100 text-indigo-600 rounded-xl">
                    <CalendarOff className="w-6 h-6" />
                </div>
                <div>
                    <h2 className="text-xl font-bold text-gray-900">Períodos de Ausencia</h2>
                    <p className="text-sm text-gray-500">
                        Gestiona vacaciones y bajas. Se bloquearán en la agenda general.
                    </p>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                {/* Formulario de Alta */}
                <div className="lg:col-span-1 bg-white border border-gray-200 rounded-xl p-5 shadow-sm h-fit">
                    <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
                        <Plus className="w-4 h-4 text-indigo-500" />
                        Nueva Ausencia
                    </h3>

                    <form onSubmit={handleSubmit} className="space-y-4">
                        {errorLocal && (
                            <div className="p-3 bg-red-50 text-red-700 text-xs rounded-lg flex items-start gap-2 border border-red-100">
                                <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                                <span>{errorLocal}</span>
                            </div>
                        )}

                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Empleado</label>
                            <select
                                value={userId}
                                onChange={(e) => setUserId(e.target.value)}
                                className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-gray-50 p-2 border"
                            >
                                <option value="">-- Seleccionar Operario --</option>
                                {tecnicos.map(t => (
                                    <option key={t.id} value={t.id}>{t.name} ({t.email})</option>
                                ))}
                            </select>
                        </div>

                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Tipo de Ausencia</label>
                            <select
                                value={tipo}
                                onChange={(e) => setTipo(e.target.value)}
                                className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-gray-50 p-2 border"
                            >
                                <option value="VACACIONES">Vacaciones</option>
                                <option value="BAJA_MEDICA">Baja Médica</option>
                                <option value="ASUNTOS_PROPIOS">Asuntos Propios</option>
                            </select>
                        </div>

                        <div className="grid grid-cols-2 gap-3">
                            <div>
                                <label className="block text-xs font-semibold text-gray-700 mb-1">Día Comienzo</label>
                                <input
                                    type="date"
                                    value={fechaInicio}
                                    onChange={(e) => setFechaInicio(e.target.value)}
                                    className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-gray-50 p-2 border"
                                />
                            </div>
                            <div>
                                <label className="block text-xs font-semibold text-gray-700 mb-1">Día Final</label>
                                <input
                                    type="date"
                                    value={fechaFin}
                                    onChange={(e) => setFechaFin(e.target.value)}
                                    className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-gray-50 p-2 border"
                                />
                            </div>
                        </div>

                        <div>
                            <label className="block text-xs font-semibold text-gray-700 mb-1">Notas / Motivo (Opcional)</label>
                            <textarea
                                value={notas}
                                onChange={(e) => setNotas(e.target.value)}
                                rows={2}
                                className="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm bg-gray-50 p-2 border resize-none"
                                placeholder="Ej: Vacaciones de verano aprobadas..."
                            />
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full mt-2 flex items-center justify-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white py-2.5 px-4 rounded-xl font-medium transition-colors shadow-sm disabled:opacity-70"
                        >
                            {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Registrar Ausencia'}
                        </button>
                    </form>
                </div>

                {/* Listado Histórico */}
                <div className="lg:col-span-2">
                    <div className="bg-white border text-sm border-gray-200 rounded-xl shadow-sm overflow-hidden">
                        {localAusencias.length === 0 ? (
                            <div className="p-8 text-center text-gray-500 flex flex-col items-center">
                                <CalendarOff className="w-10 h-10 text-gray-300 mb-3" />
                                <p>No hay ausencias ni vacaciones registradas.</p>
                            </div>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full text-left border-collapse">
                                    <thead>
                                        <tr className="bg-gray-50 border-b border-gray-200 text-xs text-gray-500 uppercase">
                                            <th className="px-4 py-3 font-semibold">Empleado</th>
                                            <th className="px-4 py-3 font-semibold">Rango</th>
                                            <th className="px-4 py-3 font-semibold">Tipo</th>
                                            <th className="px-4 py-3 font-semibold text-right">Acción</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-100">
                                        {localAusencias.map(aus => (
                                            <tr key={aus.id} className="hover:bg-gray-50/50">
                                                <td className="px-4 py-3 font-medium text-gray-900 flex items-center gap-2">
                                                    <User className="w-4 h-4 text-gray-400" />
                                                    {aus.user?.name || 'Usuario borrado'}
                                                </td>
                                                <td className="px-4 py-3 text-gray-600">
                                                    {new Date(aus.fechaInicio).toLocaleDateString()} - {new Date(aus.fechaFin).toLocaleDateString()}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border ${getTipoColor(aus.tipo)}`}>
                                                        {getTipoLabel(aus.tipo)}
                                                    </span>
                                                    {aus.notas && <p className="text-[10px] text-gray-500 mt-1 truncate max-w-[150px]" title={aus.notas}>{aus.notas}</p>}
                                                </td>
                                                <td className="px-4 py-3 text-right">
                                                    <button
                                                        onClick={() => handleDelete(aus.id)}
                                                        disabled={loading}
                                                        className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                                        title="Eliminar registro"
                                                    >
                                                        <Trash2 className="w-4 h-4" />
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>
                </div>

            </div>

        </div>
    );
}
