import React, { useEffect, useRef, useState } from 'react';
import { Head, router, useForm } from '@inertiajs/react';
import {
    ArrowRight,
    Archive,
    ArchiveRestore,
    Calendar,
    Check,
    ChevronDown,
    CircleAlert,
    FileText,
    Folder,
    FolderPlus,
    Inbox as InboxIcon,
    Loader2,
    Pencil,
    Search,
    Star,
    Trash2,
    X,
} from 'lucide-react';
import AppLayout from '@/Layouts/AppLayout';
import { Pagination } from '@/Components/ui/Workspace';
import { AnimatePresence, motion } from 'motion/react';
import { useNotificationStore } from '@/stores/useNotificationStore';
import api from '@/lib/axios';
import { confirmAction } from '@/lib/confirmAction';
import toast from 'react-hot-toast';

const date = (value) =>
    value
        ? new Date(value).toLocaleString('es-PE', {
              timeZone: 'America/Lima',
              day: '2-digit',
              month: 'short',
              year: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false,
          })
        : '—';

const toIsoDate = (d) => {
    const parts = new Intl.DateTimeFormat('en-CA', {
        timeZone: 'America/Lima',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
    }).formatToParts(d);
    const map = Object.fromEntries(parts.map((p) => [p.type, p.value]));
    return `${map.year}-${map.month}-${map.day}`;
};

export default function Inbox({
    notificaciones,
    filters = {},
    resumen,
    user,
    tipos = [],
    carpetas = [],
    carpetaActual,
    organizacion,
}) {
    const tipoLabels = Object.fromEntries(tipos.map((tipo) => [tipo.codigo, tipo.nombre]));
    const { openDocument } = useNotificationStore();

    const [search, setSearch] = useState(filters.q || '');
    const [estado, setEstado] = useState(filters.estado || '');
    const [tipo, setTipo] = useState(filters.tipo || '');
    const [fechaDesde, setFechaDesde] = useState(filters.fecha_desde || '');
    const [fechaHasta, setFechaHasta] = useState(filters.fecha_hasta || '');
    const [recibidosExpanded, setRecibidosExpanded] = useState(true);

    const [confirming, setConfirming] = useState(null);
    const [readingId, setReadingId] = useState(null);
    const [error, setError] = useState('');
    const [creatingFolder, setCreatingFolder] = useState(false);
    const [editingFolder, setEditingFolder] = useState(null);
    const [editingName, setEditingName] = useState('');
    const folderForm = useForm({ nombre: '' });

    const vista = filters.vista || 'recibidos';
    const title =
        vista === 'carpeta'
            ? carpetaActual?.nombre
            : {
                  recibidos: filters.estado === 'pendiente' ? 'Nuevos / Pendientes' : 'Recibidos',
                  destacados: 'Destacados',
                  archivados: 'Archivados',
              }[vista];

    const dialogRef = useRef(null);

    // Sincronizar filtros locales si cambian por navegación desde el Sidebar
    useEffect(() => {
        setSearch(filters.q || '');
        setEstado(filters.estado || '');
        setTipo(filters.tipo || '');
        setFechaDesde(filters.fecha_desde || '');
        setFechaHasta(filters.fecha_hasta || '');
    }, [filters.q, filters.estado, filters.tipo, filters.fecha_desde, filters.fecha_hasta]);

    useEffect(() => {
        if (!confirming) return;
        const previous = document.activeElement;
        const dialog = dialogRef.current;
        const buttons = dialog?.querySelectorAll('button');
        buttons?.[0]?.focus();
        const onKeyDown = (event) => {
            if (event.key === 'Escape' && readingId === null) setConfirming(null);
            if (event.key === 'Tab' && buttons?.length) {
                const first = buttons[0];
                const last = buttons[buttons.length - 1];
                if (event.shiftKey && document.activeElement === first) {
                    event.preventDefault();
                    last.focus();
                } else if (!event.shiftKey && document.activeElement === last) {
                    event.preventDefault();
                    first.focus();
                }
            }
        };
        dialog?.addEventListener('keydown', onKeyDown);
        return () => {
            dialog?.removeEventListener('keydown', onKeyDown);
            previous?.focus();
        };
    }, [confirming, readingId]);

    const isAdmin = ['admin', 'super_admin'].includes(user.rol);

    const filter = (
        nextEstado = estado,
        nextTipo = tipo,
        nextSearch = search,
        nextDesde = fechaDesde,
        nextHasta = fechaHasta
    ) => {
        const params = {
            ...(isAdmin ? { ver_como_casilla: 1 } : {}),
            ...(nextEstado ? { estado: nextEstado } : {}),
            ...(nextTipo ? { tipo: nextTipo } : {}),
            ...(nextSearch ? { q: nextSearch } : {}),
            ...(nextDesde ? { fecha_desde: nextDesde } : {}),
            ...(nextHasta ? { fecha_hasta: nextHasta } : {}),
            ...(vista !== 'recibidos' ? { vista } : {}),
            ...(vista === 'carpeta' ? { carpeta: filters.carpeta } : {}),
        };
        router.get('/inbox', params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const applyDatePreset = (preset) => {
        const now = new Date();
        const todayStr = toIsoDate(now);
        let desde = '';
        let hasta = todayStr;

        if (preset === 'hoy') {
            desde = todayStr;
        } else if (preset === '7d') {
            const d = new Date(now);
            d.setDate(d.getDate() - 7);
            desde = toIsoDate(d);
        } else if (preset === 'mes') {
            const d = new Date(now.getFullYear(), now.getMonth(), 1);
            desde = toIsoDate(d);
        } else if (preset === 'limpiar') {
            desde = '';
            hasta = '';
        }

        setFechaDesde(desde);
        setFechaHasta(hasta);
        filter(estado, tipo, search, desde, hasta);
    };

    const open = async (notif) => {
        setError('');
        setReadingId(notif.id);
        try {
            const { data } = await api.post(`/casilla/notificaciones/${notif.id}/leer`);
            setConfirming(null);
            openDocument(data.notificacion, data.download_url, data.constancia_url);
            router.reload({ only: ['notificaciones', 'unreadCount', 'resumen', 'auth'] });
        } catch (err) {
            setError(
                err.response?.data?.message ||
                    'No se pudo abrir el documento. Inténtalo nuevamente.'
            );
            setConfirming(null);
        } finally {
            setReadingId(null);
        }
    };

    const navigateView = (nextVista, folderId = null, nextEstado = '') => {
        setEstado(nextEstado);
        setTipo('');
        setSearch('');
        setFechaDesde('');
        setFechaHasta('');
        setError('');
        router.get(
            '/inbox',
            {
                ...(isAdmin ? { ver_como_casilla: 1 } : {}),
                ...(nextVista !== 'recibidos' ? { vista: nextVista } : {}),
                ...(nextEstado ? { estado: nextEstado } : {}),
                ...(folderId ? { carpeta: folderId } : {}),
            },
            { preserveScroll: true }
        );
    };

    const organize = (notif, data) => {
        setError('');
        router.patch(`/casilla/notificaciones/${notif.id}/organizar`, data, {
            preserveScroll: true,
            onSuccess: () => {
                if ('archivada' in data)
                    toast.success(
                        data.archivada
                            ? 'Documento archivado.'
                            : 'Documento devuelto a recibidos.'
                    );
                else if ('carpeta_id' in data) toast.success('Carpeta actualizada.');
            },
            onError: () => {
                setError('No se pudo actualizar la organización. Inténtalo nuevamente.');
                toast.error('No se pudo actualizar la organización.');
            },
        });
    };

    const deleteFolder = async (folder) => {
        if (
            await confirmAction({
                title: '¿Eliminar carpeta?',
                text: `La carpeta ${folder.nombre} se eliminará. Sus documentos se conservarán.`,
                confirmText: 'Eliminar carpeta',
                destructive: true,
            })
        )
            router.delete(`/casilla/carpetas/${folder.id}`, {
                onError: () => toast.error('No se pudo eliminar la carpeta.'),
            });
    };

    const createFolder = (event) => {
        event.preventDefault();
        folderForm.post('/casilla/carpetas', {
            preserveScroll: true,
            onSuccess: () => {
                folderForm.reset();
                setCreatingFolder(false);
            },
        });
    };

    const selectEstado = (value) => {
        setEstado(value);
        filter(value, tipo, search, fechaDesde, fechaHasta);
    };

    const clear = () => {
        setEstado('');
        setTipo('');
        setSearch('');
        setFechaDesde('');
        setFechaHasta('');
        filter('', '', '', '', '');
    };

    const hasActiveFilters = Boolean(
        estado || tipo || filters.q || fechaDesde || fechaHasta
    );

    const stats = [
        {
            label: 'Por revisar',
            value: resumen.pendientes,
            hint: resumen.pendientes
                ? `Incluye archivados · más antiguo: ${date(resumen.pendiente_mas_antigua)}`
                : 'No tienes lecturas pendientes',
            key: 'pendiente',
            icon: CircleAlert,
        },
        {
            label: 'Leídos',
            value: resumen.leidos,
            hint: 'Con lectura registrada',
            key: 'leido',
            icon: Check,
        },
        {
            label: 'Recibidos',
            value: resumen.total,
            hint: 'Incluye notificaciones anuladas',
            key: '',
            icon: InboxIcon,
        },
    ];

    const isRecibidosRoot = vista === 'recibidos' && estado !== 'pendiente';
    const isPendientesView = vista === 'recibidos' && estado === 'pendiente';

    return (
        <AppLayout>
            <Head title="Mi casilla" />
            <div className="mb-8 flex flex-col gap-4 border-b border-slate-200/80 pb-6 sm:flex-row sm:items-end sm:justify-between">
                <div>
                    <p className="mb-2 text-xs font-semibold uppercase tracking-[0.14em] text-[#657482]">
                        Tu espacio personal
                    </p>
                    <h1 className="text-3xl font-semibold tracking-tight text-[#1b2631]">
                        Mi casilla
                    </h1>
                    <p className="mt-2 text-sm text-slate-500">
                        Revisa tus documentos y consulta el estado de cada notificación.
                    </p>
                </div>
                <div className="text-sm text-slate-500">
                    <span className="font-semibold text-slate-700">{user.name}</span>
                    <span className="mx-2 text-slate-300">/</span>DNI {user.dni}
                </div>
            </div>

            <section
                aria-label="Resumen de tu casilla"
                className="surface-card mb-6 grid overflow-hidden sm:grid-cols-3"
            >
                {stats.map(({ label, value, hint, icon: Icon }) => (
                    <div
                        key={label}
                        className="flex items-start gap-4 border-b border-slate-100 px-5 py-4 last:border-0 sm:border-b-0 sm:border-r sm:px-6 sm:py-5"
                    >
                        <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[#edf6fa] text-[#277aa5]">
                            <Icon className="h-5 w-5" />
                        </span>
                        <div className="min-w-0">
                            <div className="flex flex-wrap items-baseline gap-x-3">
                                <span className="text-2xl font-semibold tabular-nums tracking-tight text-[#173650]">
                                    {value}
                                </span>
                                <span className="text-sm font-semibold text-[#36546b]">
                                    {label}
                                </span>
                            </div>
                            <p className="mt-1 text-xs leading-5 text-slate-500">{hint}</p>
                        </div>
                    </div>
                ))}
            </section>

            <div className="grid items-start gap-5 @min-[800px]/workspace:grid-cols-[235px_minmax(0,1fr)]">
                <aside
                    className="h-fit rounded-xl border border-[#dce6ed] bg-[#eaf1f5]/60 p-3"
                    aria-label="Organización de la casilla"
                >
                    <div className="px-3 pb-3 pt-2">
                        <p className="text-[11px] font-semibold uppercase tracking-[0.14em] text-[#7a8996]">
                            Mi espacio
                        </p>
                        <h2 className="mt-1 text-sm font-semibold text-[#172b3e]">Bandeja</h2>
                    </div>

                    <nav aria-label="Vistas de la bandeja" className="space-y-1">
                        {/* Recibidos con barra desplegable para sus sub-bandejas */}
                        <div>
                            <div
                                className={`flex w-full items-center rounded-lg px-2.5 py-2 text-sm transition ${
                                    isRecibidosRoot
                                        ? 'bg-[#e8edf1] font-semibold text-[#163450]'
                                        : 'text-slate-700 hover:bg-slate-50'
                                }`}
                            >
                                <button
                                    type="button"
                                    onClick={() => navigateView('recibidos')}
                                    aria-current={isRecibidosRoot ? 'page' : undefined}
                                    className="flex flex-1 items-center gap-2.5 text-left min-w-0"
                                >
                                    <InboxIcon className="h-4 w-4 shrink-0 text-[#163450]" />
                                    <span className="flex-1 truncate">Recibidos</span>
                                </button>
                                <span className="mr-1 text-xs tabular-nums text-slate-500">
                                    {organizacion.recibidos}
                                </span>
                                <button
                                    type="button"
                                    onClick={() => setRecibidosExpanded((prev) => !prev)}
                                    aria-expanded={recibidosExpanded}
                                    aria-label={
                                        recibidosExpanded
                                            ? 'Contraer vistas dentro de Recibidos'
                                            : 'Desplegar vistas dentro de Recibidos'
                                    }
                                    title={
                                        recibidosExpanded
                                            ? 'Contraer Recibidos'
                                            : 'Desplegar Recibidos'
                                    }
                                    className="rounded-md p-1 text-slate-400 hover:bg-slate-200/70 hover:text-[#163450] transition"
                                >
                                    <ChevronDown
                                        className={`h-3.5 w-3.5 transition-transform duration-200 ${
                                            !recibidosExpanded ? '-rotate-90' : ''
                                        }`}
                                    />
                                </button>
                            </div>

                            <AnimatePresence initial={false}>
                                {recibidosExpanded && (
                                    <motion.div
                                        initial={{ height: 0, opacity: 0 }}
                                        animate={{ height: 'auto', opacity: 1 }}
                                        exit={{ height: 0, opacity: 0 }}
                                        transition={{ duration: 0.18, ease: 'easeInOut' }}
                                        className="overflow-hidden"
                                    >
                                        <div className="ml-3.5 mt-1 space-y-1 border-l-2 border-[#cbd8e3] pl-2">
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    navigateView('recibidos', null, 'pendiente')
                                                }
                                                aria-current={isPendientesView ? 'page' : undefined}
                                                className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-xs sm:text-sm transition ${
                                                    isPendientesView
                                                        ? 'bg-[#e8edf1] font-semibold text-[#163450]'
                                                        : 'text-slate-600 hover:bg-slate-50'
                                                }`}
                                            >
                                                <CircleAlert className="h-3.5 w-3.5 shrink-0 text-amber-600" />
                                                <span className="flex-1 truncate">
                                                    Nuevos / Pendientes
                                                </span>
                                                <span className="text-xs tabular-nums font-semibold text-amber-700">
                                                    {resumen.pendientes}
                                                </span>
                                            </button>

                                            <button
                                                type="button"
                                                onClick={() => navigateView('destacados')}
                                                aria-current={
                                                    vista === 'destacados' ? 'page' : undefined
                                                }
                                                className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-xs sm:text-sm transition ${
                                                    vista === 'destacados'
                                                        ? 'bg-[#e8edf1] font-semibold text-[#163450]'
                                                        : 'text-slate-600 hover:bg-slate-50'
                                                }`}
                                            >
                                                <Star className="h-3.5 w-3.5 shrink-0 text-amber-500" />
                                                <span className="flex-1 truncate">Destacados</span>
                                                <span className="text-xs tabular-nums text-slate-500">
                                                    {organizacion.destacados}
                                                </span>
                                            </button>

                                            <button
                                                type="button"
                                                onClick={() => navigateView('archivados')}
                                                aria-current={
                                                    vista === 'archivados' ? 'page' : undefined
                                                }
                                                className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-xs sm:text-sm transition ${
                                                    vista === 'archivados'
                                                        ? 'bg-[#e8edf1] font-semibold text-[#163450]'
                                                        : 'text-slate-600 hover:bg-slate-50'
                                                }`}
                                            >
                                                <Archive className="h-3.5 w-3.5 shrink-0 text-slate-500" />
                                                <span className="flex-1 truncate">Archivados</span>
                                                <span className="text-xs tabular-nums text-slate-500">
                                                    {organizacion.archivados}
                                                </span>
                                            </button>
                                        </div>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </div>
                    </nav>

                    <div className="mt-5 flex items-center justify-between px-3">
                        <span className="text-[11px] font-semibold uppercase tracking-[0.14em] text-[#7a8996]">
                            Carpetas
                        </span>
                        <button
                            type="button"
                            onClick={() => {
                                setCreatingFolder(!creatingFolder);
                                folderForm.clearErrors();
                            }}
                            aria-label="Crear carpeta"
                            title="Crear carpeta"
                            className="rounded-md p-1.5 text-[#365a7c] hover:bg-[#e8edf1]"
                        >
                            <FolderPlus className="h-4 w-4" />
                        </button>
                    </div>

                    {creatingFolder && (
                        <form onSubmit={createFolder} className="relative mt-2 px-2">
                            <label htmlFor="folder-name" className="sr-only">
                                Nombre de carpeta
                            </label>
                            <input
                                autoFocus
                                id="folder-name"
                                name="nombre"
                                maxLength={80}
                                required
                                value={folderForm.data.nombre}
                                onChange={(e) => folderForm.setData('nombre', e.target.value)}
                                placeholder="Nombre de carpeta"
                                className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                            />
                            {folderForm.errors.nombre && (
                                <p role="alert" className="mt-1 text-xs text-rose-700">
                                    {folderForm.errors.nombre}
                                </p>
                            )}
                            <div className="mt-2 flex gap-2">
                                <button
                                    disabled={folderForm.processing}
                                    className="rounded-md bg-[#163450] px-3 py-1.5 text-xs font-semibold text-white disabled:opacity-50"
                                >
                                    Crear
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setCreatingFolder(false)}
                                    className="px-2 text-xs text-slate-500"
                                >
                                    Cancelar
                                </button>
                            </div>
                        </form>
                    )}

                    <div className="mt-2 space-y-1">
                        {carpetas.map((folder) => (
                            <div key={folder.id} className="group flex items-center">
                                {editingFolder === folder.id ? (
                                    <form
                                        className="flex w-full gap-1 px-2"
                                        onSubmit={(e) => {
                                            e.preventDefault();
                                            router.put(
                                                `/casilla/carpetas/${folder.id}`,
                                                { nombre: editingName },
                                                {
                                                    preserveScroll: true,
                                                    onSuccess: () => setEditingFolder(null),
                                                    onError: (errors) =>
                                                        setError(
                                                            errors.nombre ||
                                                                'No se pudo renombrar la carpeta.'
                                                        ),
                                                }
                                            );
                                        }}
                                    >
                                        <input
                                            name="nombre"
                                            aria-label="Nuevo nombre de carpeta"
                                            autoFocus
                                            maxLength={80}
                                            required
                                            value={editingName}
                                            onChange={(e) => setEditingName(e.target.value)}
                                            className="min-w-0 flex-1 rounded border border-slate-300 px-2 py-1 text-sm"
                                        />
                                        <button className="text-xs font-semibold text-[#25496b]">
                                            Guardar
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setEditingFolder(null)}
                                            aria-label="Cancelar"
                                            className="p-1 text-slate-500"
                                        >
                                            <X className="h-4 w-4" />
                                        </button>
                                    </form>
                                ) : (
                                    <>
                                        <button
                                            type="button"
                                            onClick={() => navigateView('carpeta', folder.id)}
                                            aria-current={
                                                vista === 'carpeta' &&
                                                Number(filters.carpeta) === folder.id
                                                    ? 'page'
                                                    : undefined
                                            }
                                            className={`flex min-w-0 flex-1 items-center gap-3 rounded-lg px-3 py-2 text-left text-sm ${
                                                vista === 'carpeta' &&
                                                Number(filters.carpeta) === folder.id
                                                    ? 'bg-[#e8edf1] font-semibold text-[#163450]'
                                                    : 'text-slate-600 hover:bg-slate-50'
                                            }`}
                                        >
                                            <Folder className="h-4 w-4 shrink-0" />
                                            <span className="flex-1 truncate">{folder.nombre}</span>
                                            <span className="text-xs text-slate-400">
                                                {folder.total}
                                            </span>
                                        </button>
                                        <button
                                            type="button"
                                            title="Renombrar carpeta"
                                            aria-label={`Renombrar ${folder.nombre}`}
                                            onClick={() => {
                                                setEditingFolder(folder.id);
                                                setEditingName(folder.nombre);
                                            }}
                                            className="p-1.5 text-slate-400 hover:text-[#163450]"
                                        >
                                            <Pencil className="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            type="button"
                                            title="Eliminar carpeta"
                                            aria-label={`Eliminar ${folder.nombre}`}
                                            onClick={() => deleteFolder(folder)}
                                            className="p-1.5 text-slate-400 hover:text-rose-700"
                                        >
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </button>
                                    </>
                                )}
                            </div>
                        ))}
                        {carpetas.length === 0 && !creatingFolder && (
                            <p className="px-3 py-2 text-xs leading-5 text-slate-400">
                                Crea carpetas para organizar tus documentos.
                            </p>
                        )}
                    </div>

                    <div className="mt-5 rounded-lg bg-[#f4f6f8] p-3 text-xs leading-5 text-[#60707e]">
                        Archivar organiza tu bandeja; no registra la lectura ni elimina el
                        documento.
                    </div>
                </aside>

                <section className="surface-card @container/inbox min-w-0 overflow-hidden">
                    <div className="border-b border-slate-100 p-5 sm:p-6">
                        <div className="flex flex-col gap-2 @min-[525px]/inbox:flex-row sm:items-center sm:justify-between">
                            <div>
                                <h2 className="text-lg font-semibold text-slate-900">{title}</h2>
                                <p className="mt-1 text-sm text-slate-500">
                                    {notificaciones.total}{' '}
                                    {notificaciones.total === 1 ? 'resultado' : 'resultados'}
                                </p>
                            </div>
                            {hasActiveFilters && (
                                <button
                                    type="button"
                                    onClick={clear}
                                    className="self-start text-sm font-semibold text-[#25496b] hover:underline"
                                >
                                    Limpiar filtros
                                </button>
                            )}
                        </div>

                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                filter(estado, tipo, search, fechaDesde, fechaHasta);
                            }}
                            className="mt-5 space-y-3"
                        >
                            {/* Fila 1: Búsqueda por texto y tipo de documento */}
                            <div className="flex flex-col gap-2 @min-[525px]/inbox:flex-row">
                                <div className="relative flex-1">
                                    <Search className="absolute left-3 top-3 h-4 w-4 text-slate-400" />
                                    <input
                                        name="q"
                                        aria-label="Buscar documento"
                                        value={search}
                                        onChange={(e) => setSearch(e.target.value)}
                                        placeholder="Buscar por asunto o número"
                                        className="h-10 w-full rounded-lg border border-slate-300 pl-9 pr-3 text-sm"
                                    />
                                </div>
                                <select
                                    name="tipo"
                                    aria-label="Tipo de documento"
                                    value={tipo}
                                    onChange={(e) => {
                                        setTipo(e.target.value);
                                        filter(
                                            estado,
                                            e.target.value,
                                            search,
                                            fechaDesde,
                                            fechaHasta
                                        );
                                    }}
                                    className="h-10 rounded-lg border border-slate-300 bg-white px-3 text-sm text-slate-700"
                                >
                                    <option value="">Todos los tipos</option>
                                    {tipos.map((item) => (
                                        <option key={item.codigo} value={item.codigo}>
                                            {item.nombre}
                                        </option>
                                    ))}
                                </select>
                                <button
                                    type="submit"
                                    className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                                >
                                    Buscar
                                </button>
                            </div>

                            {/* Fila 2: Filtro por rango de fechas y atajos rápidos */}
                            <div className="flex flex-wrap items-center gap-2 rounded-xl border border-slate-200/80 bg-slate-50/70 p-2.5">
                                <div className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 px-1.5">
                                    <Calendar className="h-3.5 w-3.5 text-[#25496b]" />
                                    <span>Filtrar por fecha:</span>
                                </div>

                                <div className="flex flex-wrap items-center gap-2">
                                    <label className="flex items-center gap-1.5 text-xs text-slate-600">
                                        <span className="font-medium text-slate-500">Desde</span>
                                        <input
                                            type="date"
                                            name="fecha_desde"
                                            aria-label="Fecha desde"
                                            value={fechaDesde}
                                            max={fechaHasta || undefined}
                                            onChange={(e) => {
                                                const val = e.target.value;
                                                setFechaDesde(val);
                                                filter(estado, tipo, search, val, fechaHasta);
                                            }}
                                            className="h-8 rounded-lg border border-slate-300 bg-white px-2.5 text-xs text-slate-700 focus:border-[#163450] focus:outline-none"
                                        />
                                    </label>

                                    <label className="flex items-center gap-1.5 text-xs text-slate-600">
                                        <span className="font-medium text-slate-500">Hasta</span>
                                        <input
                                            type="date"
                                            name="fecha_hasta"
                                            aria-label="Fecha hasta"
                                            value={fechaHasta}
                                            min={fechaDesde || undefined}
                                            onChange={(e) => {
                                                const val = e.target.value;
                                                setFechaHasta(val);
                                                filter(estado, tipo, search, fechaDesde, val);
                                            }}
                                            className="h-8 rounded-lg border border-slate-300 bg-white px-2.5 text-xs text-slate-700 focus:border-[#163450] focus:outline-none"
                                        />
                                    </label>
                                </div>

                                <div className="flex flex-wrap items-center gap-1 sm:ml-auto">
                                    {[
                                        ['hoy', 'Hoy'],
                                        ['7d', 'Últimos 7 días'],
                                        ['mes', 'Este mes'],
                                    ].map(([presetKey, presetLabel]) => (
                                        <button
                                            key={presetKey}
                                            type="button"
                                            onClick={() => applyDatePreset(presetKey)}
                                            className="rounded-lg border border-slate-200 bg-white px-2.5 py-1 text-xs font-medium text-slate-600 hover:border-[#163450] hover:text-[#163450] transition"
                                        >
                                            {presetLabel}
                                        </button>
                                    ))}
                                    {(fechaDesde || fechaHasta) && (
                                        <button
                                            type="button"
                                            onClick={() => applyDatePreset('limpiar')}
                                            title="Quitar filtro de fechas"
                                            className="inline-flex items-center gap-1 rounded-lg border border-rose-200 bg-rose-50 px-2 py-1 text-xs font-semibold text-rose-700 hover:bg-rose-100 transition"
                                        >
                                            <X className="h-3 w-3" />
                                            <span>Quitar fechas</span>
                                        </button>
                                    )}
                                </div>
                            </div>
                        </form>

                        <div
                            className="mt-4 flex flex-wrap gap-1 border-t border-slate-100 pt-3"
                            aria-label="Filtrar por estado"
                        >
                            {[
                                ['', 'Todos'],
                                ['pendiente', 'Pendientes'],
                                ['leido', 'Leídos'],
                                ['anulado', 'Anulados'],
                            ].map(([key, label]) => (
                                <button
                                    key={label}
                                    type="button"
                                    aria-pressed={estado === key}
                                    onClick={() => selectEstado(key)}
                                    className={`rounded-lg px-3 py-2 text-sm font-medium ${
                                        estado === key
                                            ? 'bg-[#173e5c] text-white'
                                            : 'text-slate-500 hover:bg-slate-50'
                                    }`}
                                >
                                    {label}
                                </button>
                            ))}
                        </div>
                    </div>

                    {error && (
                        <div
                            role="alert"
                            className="mx-5 mt-4 rounded-lg bg-rose-50 p-3 text-sm text-rose-800"
                        >
                            {error}
                        </div>
                    )}

                    {notificaciones.data.length === 0 ? (
                        <div className="px-6 py-16 text-center">
                            <span className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-[#edf6fa] text-[#4784a5]">
                                <InboxIcon className="h-6 w-6" />
                            </span>
                            <h3 className="mt-4 font-semibold text-slate-800">
                                No hay documentos para mostrar
                            </h3>
                            <p className="mt-2 text-sm text-slate-500">
                                Prueba otros filtros o vuelve más tarde.
                            </p>
                            {hasActiveFilters && (
                                <button
                                    type="button"
                                    onClick={clear}
                                    className="mt-4 text-sm font-semibold text-[#25496b] hover:underline"
                                >
                                    Ver todos los documentos
                                </button>
                            )}
                        </div>
                    ) : (
                        <div className="divide-y divide-slate-100">
                            {notificaciones.data.map((notif) => {
                                const pending = notif.estado === 'pendiente';
                                const cancelled = notif.estado === 'anulado';
                                return (
                                    <motion.article
                                        key={notif.id}
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        transition={{ duration: 0.2 }}
                                        className="flex flex-col gap-4 px-5 py-5 transition-colors hover:bg-slate-50/70 sm:px-6 @min-[780px]/inbox:flex-row @min-[780px]/inbox:items-center"
                                    >
                                        <div
                                            className={`hidden h-11 w-11 shrink-0 items-center justify-center rounded-lg sm:flex ${
                                                pending
                                                    ? 'bg-[#e7ecf0] text-[#25496b]'
                                                    : 'bg-slate-100 text-slate-500'
                                            }`}
                                        >
                                            <FileText className="h-5 w-5" />
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <span className="text-xs font-semibold uppercase tracking-wide text-slate-500">
                                                    {tipoLabels[notif.documento?.tipo_documento] ||
                                                        notif.documento?.tipo_documento}
                                                </span>
                                                <span
                                                    className={`rounded-full px-2.5 py-1 text-xs font-medium ${
                                                        pending
                                                            ? 'bg-amber-50 text-amber-800'
                                                            : cancelled
                                                              ? 'bg-slate-100 text-slate-600'
                                                              : 'bg-emerald-50 text-emerald-700'
                                                    }`}
                                                >
                                                    {pending
                                                        ? 'Pendiente'
                                                        : cancelled
                                                          ? 'Anulado'
                                                          : 'Leído'}
                                                </span>
                                            </div>
                                            <h3 className="mt-2 break-words text-sm font-semibold leading-5 text-slate-900">
                                                {notif.documento?.titulo}
                                            </h3>
                                            <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
                                                <span>Recibido: {date(notif.fecha_envio)}</span>
                                                {notif.fecha_lectura && (
                                                    <span>Leído: {date(notif.fecha_lectura)}</span>
                                                )}
                                            </div>
                                        </div>
                                        <div className="flex flex-wrap items-center gap-2">
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    organize(notif, {
                                                        destacada: !notif.destacada,
                                                    })
                                                }
                                                aria-label={
                                                    notif.destacada
                                                        ? 'Quitar de destacados'
                                                        : 'Marcar como destacado'
                                                }
                                                aria-pressed={notif.destacada}
                                                title={
                                                    notif.destacada
                                                        ? 'Quitar de destacados'
                                                        : 'Destacar'
                                                }
                                                className={`rounded-lg border border-slate-200 p-2.5 hover:bg-amber-50 ${
                                                    notif.destacada
                                                        ? 'text-amber-600'
                                                        : 'text-slate-400'
                                                }`}
                                            >
                                                <Star
                                                    className={`h-4 w-4 ${
                                                        notif.destacada ? 'fill-current' : ''
                                                    }`}
                                                />
                                            </button>
                                            <select
                                                name={`carpeta_${notif.id}`}
                                                aria-label={`Mover ${notif.documento?.titulo} a carpeta`}
                                                value={notif.carpeta_id || ''}
                                                onChange={(e) =>
                                                    organize(notif, {
                                                        carpeta_id: e.target.value
                                                            ? Number(e.target.value)
                                                            : null,
                                                    })
                                                }
                                                className="max-w-36 rounded-lg border border-slate-200 bg-white px-2 py-2 text-xs text-slate-600"
                                            >
                                                <option value="">Sin carpeta</option>
                                                {carpetas.map((folder) => (
                                                    <option key={folder.id} value={folder.id}>
                                                        {folder.nombre}
                                                    </option>
                                                ))}
                                            </select>
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    organize(notif, {
                                                        archivada: !notif.archivada,
                                                    })
                                                }
                                                aria-label={
                                                    notif.archivada ? 'Desarchivar' : 'Archivar'
                                                }
                                                title={
                                                    notif.archivada ? 'Desarchivar' : 'Archivar'
                                                }
                                                className="rounded-lg border border-slate-200 p-2.5 text-slate-500 hover:bg-slate-50"
                                            >
                                                {notif.archivada ? (
                                                    <ArchiveRestore className="h-4 w-4" />
                                                ) : (
                                                    <Archive className="h-4 w-4" />
                                                )}
                                            </button>
                                        </div>
                                        {cancelled ? (
                                            <span className="text-xs text-slate-400">
                                                No disponible
                                            </span>
                                        ) : (
                                            <button
                                                type="button"
                                                disabled={readingId !== null}
                                                onClick={() =>
                                                    pending ? setConfirming(notif) : open(notif)
                                                }
                                                className={`inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold transition disabled:opacity-50 ${
                                                    pending
                                                        ? 'bg-[#163450] text-white hover:bg-[#0e273f]'
                                                        : 'border border-slate-200 text-[#25496b] hover:bg-[#f3f6f8]'
                                                }`}
                                            >
                                                {readingId === notif.id ? (
                                                    <Loader2 className="h-4 w-4 animate-spin" />
                                                ) : null}
                                                {pending ? 'Revisar documento' : 'Ver documento'}{' '}
                                                <ArrowRight className="h-4 w-4" />
                                            </button>
                                        )}
                                    </motion.article>
                                );
                            })}
                        </div>
                    )}
                    <Pagination data={notificaciones} />
                </section>
            </div>

            {confirming && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-[#102435]/55 p-4"
                    role="dialog"
                    aria-modal="true"
                    aria-labelledby="confirm-title"
                >
                    <div
                        ref={dialogRef}
                        className="w-full max-w-[440px] overflow-hidden rounded-2xl border border-[#dce6ed] bg-white shadow-[0_24px_70px_rgba(13,36,55,0.22)]"
                    >
                        <div className="px-6 pt-6">
                            <div className="flex items-center justify-between gap-4">
                                <div className="flex items-center gap-3">
                                    <img
                                        src="/images/logo-circular.png"
                                        alt=""
                                        className="h-8 w-8 rounded-full object-contain"
                                    />
                                    <p className="text-[10px] font-bold uppercase tracking-[0.12em] text-[#658096]">
                                        Lectura · UGEL Ambo
                                    </p>
                                </div>
                                <button
                                    type="button"
                                    onClick={() => setConfirming(null)}
                                    aria-label="Cerrar"
                                    className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700"
                                >
                                    <X className="h-5 w-5" />
                                </button>
                            </div>
                            <h2
                                id="confirm-title"
                                className="mt-6 text-xl font-semibold tracking-tight text-[#173650]"
                            >
                                Antes de abrir el documento
                            </h2>
                            <p className="mt-2 text-sm leading-6 text-[#5b6d7c]">
                                Al continuar se registrará la fecha y hora de lectura de{' '}
                                <strong className="text-[#29465b]">
                                    {confirming.documento?.titulo}
                                </strong>
                                .
                            </p>
                        </div>
                        <div className="mt-6 flex flex-wrap justify-end gap-2.5 border-t border-[#e9eff3] bg-[#f8fafc] px-6 py-4">
                            <button
                                type="button"
                                disabled={readingId !== null}
                                onClick={() => setConfirming(null)}
                                className="min-h-[42px] rounded-lg border border-[#d4e0e8] bg-white px-4 text-sm font-semibold text-[#3c5364] hover:bg-[#eef4f7] disabled:opacity-50"
                            >
                                Cancelar
                            </button>
                            <button
                                type="button"
                                disabled={readingId !== null}
                                onClick={() => open(confirming)}
                                className="min-h-[42px] rounded-lg bg-[#194b6b] px-4 text-sm font-semibold text-white hover:bg-[#123a55] disabled:opacity-50"
                            >
                                {readingId ? 'Abriendo…' : 'Registrar lectura y abrir'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}
