import { Head, router, useForm } from '@inertiajs/react';
import { CalendarX, Plus, Trash2 } from 'lucide-react';
import type { FormEvent } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { Flash } from '@/components/Flash';
import { fecha } from '@/lib/format';

type Props = {
    anio: number;
    data: { anios?: number[]; feriados?: { fecha: string; descripcion: string; diaSemana: number; cuenta: boolean }[] } | null;
};

const DIAS = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];

export default function Feriados({ anio, data }: Props) {
    const form = useForm({ fecha: '', descripcion: '' });
    const anios = Array.from(new Set([...(data?.anios ?? []), anio, anio + 1])).sort();

    const agregar = (e: FormEvent) => {
        e.preventDefault();
        form.post('/admin/feriados', { preserveScroll: true, onSuccess: () => form.reset() });
    };
    const quitar = (f: string, d: string) => {
        if (confirm(`¿Quitar el feriado del ${fecha(f)} (${d})?`)) router.delete(`/admin/feriados/${f}`, { preserveScroll: true });
    };

    return (
        <AppLayout>
            <Head title="Feriados" />
            <h1 className="flex items-center gap-2 text-2xl font-extrabold">
                <CalendarX className="size-6 text-brand" /> Feriados
            </h1>
            <p className="mb-5 text-sm text-slate-500">Los feriados no cuentan como días hábiles en los tableros. Los días hábiles son de lunes a viernes menos esta lista.</p>

            <div className="max-w-4xl rounded-2xl border border-slate-200 bg-white p-5">
                <Flash />
                <div className="mb-4 flex items-center justify-between">
                    <h2 className="font-extrabold">Feriados {anio}</h2>
                    <label className="text-xs font-semibold text-slate-500">
                        Año{' '}
                        <select value={anio} onChange={(e) => router.get('/admin/feriados', { anio: e.target.value }, { preserveState: true })} className="ml-1 rounded-lg border border-slate-200 px-2 py-1">
                            {anios.map((a) => (
                                <option key={a}>{a}</option>
                            ))}
                        </select>
                    </label>
                </div>

                <form onSubmit={agregar} className="mb-4 flex flex-wrap items-end gap-2">
                    <label className="text-[10px] font-semibold tracking-wider text-slate-400 uppercase">
                        Fecha
                        <input type="date" required value={form.data.fecha} onChange={(e) => form.setData('fecha', e.target.value)} className="mt-1 block rounded-lg border border-slate-200 px-2 py-2 text-sm text-slate-800" />
                    </label>
                    <label className="flex-1 text-[10px] font-semibold tracking-wider text-slate-400 uppercase">
                        Descripción
                        <input required maxLength={150} value={form.data.descripcion} onChange={(e) => form.setData('descripcion', e.target.value)} placeholder="Ej. Día de la Independencia" className="mt-1 block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-800" />
                    </label>
                    <button type="submit" disabled={form.processing} className="flex items-center gap-1 rounded-lg bg-brand px-4 py-2 text-sm font-bold text-white disabled:opacity-50">
                        <Plus className="size-4" /> Agregar
                    </button>
                </form>
                {(form.errors.fecha || form.errors.descripcion) && <p className="mb-3 text-sm text-red-600">{form.errors.fecha ?? form.errors.descripcion}</p>}

                <table className="w-full text-sm">
                    <thead className="text-[10px] tracking-wider text-slate-400 uppercase">
                        <tr>
                            <th className="py-2 text-left">Fecha</th>
                            <th className="text-left">Día</th>
                            <th className="text-left">Descripción</th>
                            <th />
                        </tr>
                    </thead>
                    <tbody>
                        {(data?.feriados ?? []).map((f) => (
                            <tr key={f.fecha} className="border-t border-slate-100">
                                <td className="py-2 font-semibold">{fecha(f.fecha)}</td>
                                <td className="text-slate-500">
                                    {DIAS[f.diaSemana] ?? ''}
                                    {!f.cuenta && <span className="text-[11px] text-slate-400"> (fin de semana)</span>}
                                </td>
                                <td className="font-medium">{f.descripcion}</td>
                                <td className="text-right">
                                    <button type="button" onClick={() => quitar(f.fecha, f.descripcion)} className="inline-flex items-center gap-1 rounded-lg border border-slate-200 px-2 py-1 text-xs hover:border-red-300 hover:text-red-600">
                                        <Trash2 className="size-3.5" /> Quitar
                                    </button>
                                </td>
                            </tr>
                        ))}
                        {(data?.feriados ?? []).length === 0 && (
                            <tr>
                                <td colSpan={4} className="py-6 text-center text-slate-400">
                                    Sin feriados registrados para {anio}.
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        </AppLayout>
    );
}
