import { Head, router } from '@inertiajs/react';
import { ArrowLeftRight, ChevronRight, Download, FileUp, Plus, Search, X } from 'lucide-react';
import clsx from 'clsx';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { Flash } from '@/components/Flash';
import { FilterSelect } from '@/components/dashboard';
import { Paginacion } from '@/components/Paginacion';
import { SelectBuscable, type OpcionBuscable } from '@/components/SelectBuscable';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Skeleton } from '@/components/ui/skeleton';
import { descargarExcel, getJson, postJson } from '@/lib/http';
import { int, money } from '@/lib/format';

type Filters = { buscar: string; tipo: string; estado: string; pagina: number; cliente: string };
type Fila = { cliente_id: string; cliente: string; tipo_cliente: string; tipo_sugerido?: string; responsables: number; venta_total: number | string; estado: string; activo: boolean; observacion?: string | null };
type Vendedor = { codigo_vendedor: string; vendedor: string; zona: string; nivel?: string };
type Lista = { rows: Fila[]; total: number; page: number; pageSize: number; tipos: string[]; grupos: string[]; vendedores: Vendedor[]; summary: { clientes: number; configurados: number; sinClasificar: number; sinResponsable: number } };
type Responsable = { id: number; grupo: string; zona: string; vendedor: string; codigo_vendedor: string; vigente_desde?: string };
type Detalle = {
    cliente: { cliente_id: string; cliente: string; tipo_cliente: string; tipo_sugerido?: string; activo: boolean; observacion?: string | null };
    responsables: Responsable[];
};

type Props = { filters: Filters; lista: Lista | null; detalle: Detalle | null };

const etiquetaTipo = (t: string) => t.replace(/_/g, ' ').replace('INDEP', 'INDEP.');
const opts = { preserveScroll: true, preserveState: true };
const etiqueta = 'mb-1.5 block text-sm font-medium';

/** Opciones con buscador: vendedores (código · nombre, zona como detalle) y grupos ("TODOS" = todos los grupos). */
const opcionesVendedor = (vs: Vendedor[]): OpcionBuscable[] => vs.map((v) => ({ value: v.codigo_vendedor, label: `${v.codigo_vendedor} · ${v.vendedor}`, detalle: v.zona }));
const opcionesGrupo = (gs: string[]): OpcionBuscable[] => [{ value: 'TODOS', label: 'Todos los grupos' }, ...gs.filter((g) => g !== 'TODOS').map((g) => ({ value: g, label: g }))];

/** Estados del cliente: nombre y color del punto. */
const ESTADO: Record<string, { nombre: string; punto: string; texto: string }> = {
    CONFIGURADO: { nombre: 'Configurado', punto: 'bg-emerald-600', texto: 'text-emerald-700' },
    SIN_CLASIFICAR: { nombre: 'Sin clasificar', punto: 'bg-rose-500', texto: 'text-rose-700' },
    SIN_CONFIGURAR: { nombre: 'Sin configurar', punto: 'bg-rose-500', texto: 'text-rose-700' },
    SIN_RESPONSABLE: { nombre: 'Sin responsable', punto: 'bg-amber-500', texto: 'text-amber-700' },
    INACTIVO: { nombre: 'Inactivo', punto: 'bg-slate-400', texto: 'text-slate-500' },
};

function EtiquetaEstadoCliente({ estado }: { estado: string }) {
    const e = ESTADO[estado] ?? { nombre: estado.replace(/_/g, ' '), punto: 'bg-slate-400', texto: 'text-slate-500' };
    return (
        <span className={clsx('inline-flex items-center gap-1.5 text-xs font-medium whitespace-nowrap', e.texto)}>
            <span className={clsx('size-1.5 rounded-full', e.punto)} />
            {e.nombre}
        </span>
    );
}

function Seccion({ titulo, ayuda, children }: { titulo: string; ayuda?: ReactNode; children: ReactNode }) {
    return (
        <section className="border-b border-border px-5 py-5 last:border-0">
            <h3 className="text-sm font-semibold">{titulo}</h3>
            {ayuda && <p className="mt-0.5 text-sm text-muted-foreground">{ayuda}</p>}
            <div className="mt-3">{children}</div>
        </section>
    );
}

/** "Sustituir vendedor": pasa los clientes de un vendedor a otro. Primero simula, luego aplica. */
function Sustituir({ lista, abierto, onClose }: { lista: Lista; abierto: boolean; onClose: () => void }) {
    const [saliente, setSaliente] = useState('');
    const [entrante, setEntrante] = useState('');
    const [grupo, setGrupo] = useState('TODOS');
    const [sim, setSim] = useState<Record<string, unknown> | null>(null);
    const [msg, setMsg] = useState('');
    const [ocupado, setOcupado] = useState(false);
    const [confirmar, setConfirmar] = useState(false);

    useEffect(() => {
        setSim(null);
        setConfirmar(false);
    }, [saliente, entrante, grupo]);

    const cerrar = () => {
        if (ocupado) return;
        setSaliente('');
        setEntrante('');
        setGrupo('TODOS');
        setSim(null);
        setMsg('');
        setConfirmar(false);
        onClose();
    };

    const correr = async (simular: boolean) => {
        setOcupado(true);
        setMsg('');
        try {
            const r = await postJson('/admin/clientes/sustituir', { saliente, entrante, grupo, simular });
            if (simular) setSim(r);
            else {
                setMsg(String(r.mensaje ?? r.message ?? 'Sustitución aplicada.'));
                setSim(null);
                setConfirmar(false);
                router.reload();
            }
        } catch (e) {
            setMsg(e instanceof Error ? e.message : 'Error');
        } finally {
            setOcupado(false);
        }
    };

    const nombre = (c: string) => lista.vendedores.find((v) => v.codigo_vendedor === c)?.vendedor ?? c;
    const vendedores = opcionesVendedor(lista.vendedores);

    return (
        <Dialog open={abierto} onOpenChange={(o) => !o && cerrar()}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Sustituir vendedor en clientes</DialogTitle>
                    <DialogDescription>Pasa los clientes de un vendedor a otro. Primero simula para ver el impacto; nada cambia hasta que aplicas.</DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 sm:grid-cols-2">
                    <div>
                        <label htmlFor="sust-saliente" className={etiqueta}>
                            Vendedor saliente
                        </label>
                        <SelectBuscable id="sust-saliente" value={saliente} onChange={setSaliente} options={vendedores} buscarPlaceholder="Buscar código, nombre o zona…" />
                    </div>
                    <div>
                        <label htmlFor="sust-entrante" className={etiqueta}>
                            Vendedor entrante
                        </label>
                        <SelectBuscable id="sust-entrante" value={entrante} onChange={setEntrante} options={vendedores.filter((v) => v.value !== saliente)} buscarPlaceholder="Buscar código, nombre o zona…" />
                    </div>
                    <div className="sm:col-span-2">
                        <label htmlFor="sust-grupo" className={etiqueta}>
                            Grupo
                        </label>
                        <SelectBuscable id="sust-grupo" value={grupo} onChange={setGrupo} options={opcionesGrupo(lista.grupos)} buscarPlaceholder="Buscar grupo…" />
                    </div>
                </div>
                {saliente && saliente === entrante && <p className="text-xs text-destructive">El vendedor saliente y el entrante deben ser distintos.</p>}

                {sim && (
                    <div className="rounded-lg bg-amber-50 px-4 py-3 text-sm text-amber-900">
                        <p className="font-medium">{String(sim.mensaje ?? 'Simulación lista.')}</p>
                        {Array.isArray(sim.porGrupo) && (
                            <p className="mt-1 text-xs">
                                {(sim.porGrupo as { grupo: string; asignaciones: number }[]).map((g) => `${g.grupo}: ${g.asignaciones}`).join(' · ')}
                                {sim.clientesInactivos ? ` · ${String(sim.clientesInactivos)} clientes inactivos` : ''}
                            </p>
                        )}
                        {confirmar && (
                            <p className="mt-2 border-t border-amber-200 pt-2 text-xs">
                                Se reasignarán los clientes de <strong>{nombre(saliente)}</strong> a <strong>{nombre(entrante)}</strong> ({grupo === 'TODOS' ? 'todos los grupos' : grupo}). ¿Confirmas?
                            </p>
                        )}
                    </div>
                )}
                {msg && <p className="rounded-lg bg-slate-50 px-4 py-2 text-sm">{msg}</p>}

                <DialogFooter>
                    <Button type="button" variant="outline" disabled={ocupado} onClick={cerrar}>
                        Cerrar
                    </Button>
                    {!sim ? (
                        <Button type="button" disabled={!saliente || !entrante || saliente === entrante || ocupado} onClick={() => void correr(true)}>
                            {ocupado ? 'Simulando…' : 'Simular'}
                        </Button>
                    ) : !confirmar ? (
                        <Button type="button" onClick={() => setConfirmar(true)}>
                            Aplicar sustitución
                        </Button>
                    ) : (
                        <Button type="button" disabled={ocupado} onClick={() => void correr(false)}>
                            {ocupado ? 'Aplicando…' : 'Sí, aplicar'}
                        </Button>
                    )}
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}

async function importarArchivo(file: File, setMsg: (m: string) => void) {
    const XLSX = await import('xlsx');
    const norm = (v: unknown) =>
        String(v ?? '')
            .trim()
            .normalize('NFD')
            .replace(/[̀-ͯ]/g, '')
            .toUpperCase();
    const wb = XLSX.read(await file.arrayBuffer(), { type: 'array' });
    const hoja = wb.SheetNames.find((n) => norm(n) === 'MAESTRO_CLIENTES') ?? wb.SheetNames[0];
    if (!hoja) throw new Error('El archivo no contiene hojas.');
    const datos = XLSX.utils.sheet_to_json<Record<string, unknown>>(wb.Sheets[hoja]!, { defval: '' });
    const campo = (r: Record<string, unknown>, nombres: string[]) => {
        const n: Record<string, unknown> = {};
        for (const k of Object.keys(r)) n[norm(k).replace(/[?\s]+/g, ' ').trim()] = r[k];
        for (const x of nombres) if (x in n) return n[x];
        return '';
    };
    const filas = datos
        .map((r) => {
            const a = campo(r, ['ACTIVO']);
            return {
                cliente_id: String(campo(r, ['CODIGO CLIENTE', 'CODIGO CLIENTE CANONICO', 'CLIENTE ID']) ?? '').trim(),
                tipo_cliente: String(campo(r, ['TIPO DE CLIENTE', 'TIPO CLIENTE']) ?? '').trim() || null,
                grupo: String(campo(r, ['LINEA', 'GRUPO']) ?? '').trim() || null,
                vendedor: String(campo(r, ['VENDEDOR']) ?? '').trim() || null,
                zona: String(campo(r, ['ZONA']) ?? '').trim() || null,
                activo: a === '' || (typeof a === 'boolean' ? a : !['NO', 'FALSE', 'FALSO', '0', 'F'].includes(norm(a))),
                observacion: String(campo(r, ['COMENTARIO NORMALIZADO', 'COMENTARIO', 'OBSERVACION']) ?? '').trim() || null,
            };
        })
        .filter((f) => f.cliente_id)
        .sort((a, b) => a.cliente_id.localeCompare(b.cliente_id));
    if (!filas.length) throw new Error('No encontré filas con CODIGO CLIENTE.');
    // Lotes de 500 sin partir un mismo cliente entre lotes (igual que la app anterior).
    const lotes: (typeof filas)[] = [];
    let lote: typeof filas = [];
    for (const f of filas) {
        if (lote.length >= 500 && lote[lote.length - 1]!.cliente_id !== f.cliente_id) {
            lotes.push(lote);
            lote = [];
        }
        lote.push(f);
    }
    if (lote.length) lotes.push(lote);
    let importados = 0;
    let nuevos = 0;
    let noEncontrados = 0;
    for (const [i, l] of lotes.entries()) {
        setMsg(`Importando lote ${i + 1} de ${lotes.length}…`);
        const r = await postJson<{ importados?: number; responsables_nuevos?: number; clientes_no_encontrados?: number }>('/admin/clientes/importar', { rows: l });
        importados += Number(r.importados ?? 0);
        nuevos += Number(r.responsables_nuevos ?? 0);
        noEncontrados += Number(r.clientes_no_encontrados ?? 0);
    }
    setMsg(`Importación terminada: ${importados} clientes, ${nuevos} responsables nuevos, ${noEncontrados} no encontrados.`);
    router.reload();
}

/**
 * Administración → Clientes: clasificación comercial y vendedor responsable por equipo / grupo.
 * Las pestañas filtran por estado; un clic en la fila abre su configuración en un panel deslizante (?cliente= en la URL).
 */
export default function Clientes({ filters, lista, detalle }: Props) {
    /** Visita con los filtros; los vacíos no van en la URL (?cliente= solo mientras el panel está abierto). */
    const apply = (patch: Partial<Filters>, extra: { replace?: boolean } = {}) =>
        router.get('/admin/clientes', Object.fromEntries(Object.entries({ ...filters, ...patch }).filter(([, v]) => v !== '')), { ...opts, ...extra });
    const [buscar, setBuscar] = useState(filters.buscar);
    const [sustituir, setSustituir] = useState(false);
    const [msg, setMsg] = useState('');
    const [cfg, setCfg] = useState({ tipo_cliente: '', activo: true, observacion: '' });
    const [resp, setResp] = useState({ grupo: 'TODOS', codigo_vendedor: '', zona: '' });
    const [archivo, setArchivo] = useState<File | null>(null);
    const [quitar, setQuitar] = useState<Responsable | null>(null);
    const [guardando, setGuardando] = useState(false);
    const inputArchivo = useRef<HTMLInputElement>(null);
    /**
     * Cliente abierto en el panel: se abre al instante y el detalle llega del servidor después.
     * Al cargar la página empieza cerrado aunque la URL traiga ?cliente= (p. ej. al recargar), y se limpia la URL.
     */
    const [seleccion, setSeleccion] = useState('');
    const clienteAnterior = useRef(filters.cliente);

    useEffect(() => {
        if (filters.cliente) apply({ cliente: '' }, { replace: true });
    }, []);

    useEffect(() => {
        if (filters.cliente === clienteAnterior.current) return;
        clienteAnterior.current = filters.cliente;
        setSeleccion(filters.cliente);
    }, [filters.cliente]);

    useEffect(() => {
        if (detalle) setCfg({ tipo_cliente: detalle.cliente.tipo_cliente, activo: detalle.cliente.activo, observacion: detalle.cliente.observacion ?? '' });
    }, [detalle]);

    // Al cambiar de cliente, el formulario de responsable empieza vacío.
    useEffect(() => setResp({ grupo: 'TODOS', codigo_vendedor: '', zona: '' }), [detalle?.cliente.cliente_id]);

    const abrir = (id: string) => {
        setSeleccion(id);
        apply({ cliente: id });
    };
    const cerrarPanel = () => {
        setSeleccion('');
        apply({ cliente: '' });
    };

    const s = lista?.summary;
    const pageSize = lista?.pageSize ?? 50;
    const total = lista?.total ?? 0;
    const tipos = lista?.tipos ?? [];
    const tipoDeEtiqueta = (l: string) => tipos.find((t) => etiquetaTipo(t) === l) ?? l;
    const det = detalle && detalle.cliente.cliente_id === seleccion ? detalle : null;
    const filaSel = lista?.rows.find((r) => r.cliente_id === seleccion);
    const cabecera = det?.cliente ?? filaSel;

    const exportar = async () => {
        setMsg('Generando exportación…');
        try {
            const filas = await getJson<Record<string, unknown>[]>('/admin/clientes/maestro', { buscar: filters.buscar, tipo: filters.tipo });
            const hoja = (Array.isArray(filas) ? filas : []).map((e) => ({
                'CODIGO CLIENTE': e.cliente_id,
                CLIENTE: e.cliente,
                'TIPO DE CLIENTE': e.tipo,
                ZONA: e.zona ?? '',
                VENDEDOR: e.vendedor ?? '',
                LINEA: e.linea ?? '',
                ACTIVO: e.activo === false ? 'NO' : 'SI',
                COMENTARIO: e.comentario ?? '',
            }));
            await descargarExcel(`Maestro_Clientes_${new Date().toISOString().slice(0, 10)}.xlsx`, { maestro_clientes: hoja });
            setMsg(`Exportación generada: ${hoja.length} filas.`);
        } catch (e) {
            setMsg(e instanceof Error ? e.message : 'No se pudo exportar.');
        }
    };

    const Pestana = ({ id, nombre, n, punto }: { id: string; nombre: string; n?: number; punto?: string }) => (
        <button
            type="button"
            onClick={() => apply({ estado: id, pagina: 1 })}
            className={clsx(
                'flex items-center gap-2 rounded-lg border px-3.5 py-2 text-sm transition-colors',
                filters.estado === id ? 'border-slate-300 bg-white font-semibold shadow-sm' : 'border-transparent text-muted-foreground hover:bg-white/70 hover:text-foreground',
            )}
        >
            {punto && <span className={clsx('size-2.5 rounded-full', punto)} />}
            {nombre}
            {n !== undefined && <span className={clsx('rounded-full px-1.5 text-xs tabular-nums', filters.estado === id ? 'bg-slate-100 text-foreground' : 'text-muted-foreground')}>{int(n)}</span>}
        </button>
    );

    return (
        <AppLayout>
            <Head title="Clientes" />
            <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">Clientes</h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {s ? (
                            <>
                                {int(s.configurados)} de {int(s.clientes)} clientes SAP configurados · {int(s.sinClasificar)} sin clasificar · {int(s.sinResponsable)} sin responsable.
                            </>
                        ) : (
                            'Clasificación comercial y vendedor responsable por equipo / grupo.'
                        )}
                    </p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                    <Button variant="outline" onClick={() => inputArchivo.current?.click()}>
                        <FileUp className="size-4 text-muted-foreground" /> Importar
                    </Button>
                    <input
                        ref={inputArchivo}
                        type="file"
                        accept=".xlsx,.xls"
                        className="hidden"
                        onChange={(e) => {
                            const f = e.target.files?.[0];
                            e.target.value = '';
                            if (f) setArchivo(f);
                        }}
                    />
                    <Button variant="outline" onClick={() => void exportar()}>
                        <Download className="size-4 text-muted-foreground" /> Exportar
                    </Button>
                    <Button onClick={() => setSustituir(true)} disabled={!lista}>
                        <ArrowLeftRight className="size-4" /> Sustituir vendedor
                    </Button>
                </div>
            </div>

            <Flash />
            {msg && (
                <div className="mb-4 flex items-center justify-between gap-3 rounded-lg border border-border bg-white px-4 py-2.5 text-sm">
                    <span>{msg}</span>
                    <button type="button" onClick={() => setMsg('')} className="text-muted-foreground hover:text-foreground" aria-label="Cerrar mensaje">
                        <X className="size-4" />
                    </button>
                </div>
            )}

            {/* Estados */}
            <div className="mb-4 flex flex-wrap gap-1 rounded-xl bg-slate-100/80 p-1">
                <Pestana id="TODOS" nombre="Todos" n={s?.clientes} />
                <Pestana id="CONFIGURADO" nombre="Configurados" n={s?.configurados} punto={ESTADO.CONFIGURADO!.punto} />
                <Pestana id="SIN_CLASIFICAR" nombre="Sin clasificar" punto={ESTADO.SIN_CLASIFICAR!.punto} />
                <Pestana id="SIN_CONFIGURAR" nombre="Sin configurar" punto={ESTADO.SIN_CONFIGURAR!.punto} />
                <Pestana id="SIN_RESPONSABLE" nombre="Sin responsable" n={s?.sinResponsable} punto={ESTADO.SIN_RESPONSABLE!.punto} />
                <Pestana id="INACTIVO" nombre="Inactivos" punto={ESTADO.INACTIVO!.punto} />
            </div>

            {/* Lista */}
            <div className="overflow-hidden rounded-xl border border-border bg-white">
                <div className="flex flex-wrap items-center gap-2 border-b border-border p-3">
                    <form
                        className="flex min-w-60 flex-1 flex-wrap items-center gap-2"
                        onSubmit={(e) => {
                            e.preventDefault();
                            apply({ buscar: buscar.trim(), pagina: 1 });
                        }}
                    >
                        <div className="relative min-w-60 flex-1 sm:max-w-80">
                            <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                            <Input value={buscar} onChange={(e) => setBuscar(e.target.value)} placeholder="Buscar por código o nombre" className="h-10 pl-9" />
                        </div>
                        <Button type="submit" variant="outline" className="h-10">
                            Buscar
                        </Button>
                        {filters.buscar !== '' && (
                            <Button
                                type="button"
                                variant="ghost"
                                className="h-10 text-muted-foreground"
                                onClick={() => {
                                    setBuscar('');
                                    apply({ buscar: '', pagina: 1 });
                                }}
                            >
                                <X className="size-4" /> Limpiar
                            </Button>
                        )}
                    </form>
                    <FilterSelect
                        label="Tipo"
                        value={filters.tipo === 'TODOS' ? 'TODOS' : etiquetaTipo(filters.tipo)}
                        all="TODOS"
                        options={tipos.map(etiquetaTipo)}
                        onChange={(v) => apply({ tipo: v === 'TODOS' ? 'TODOS' : tipoDeEtiqueta(v), pagina: 1 })}
                    />
                </div>

                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead>
                            <tr className="border-b border-border bg-slate-50 text-left text-xs text-muted-foreground">
                                <th className="px-4 py-3 font-medium">Cliente</th>
                                <th className="px-4 py-3 font-medium">Tipo</th>
                                <th className="px-4 py-3 text-center font-medium">Responsables</th>
                                <th className="px-4 py-3 text-right font-medium">Venta ref.</th>
                                <th className="px-4 py-3 font-medium">Estado</th>
                                <th className="w-10" />
                            </tr>
                        </thead>
                        <tbody>
                            {(lista?.rows ?? []).map((c) => {
                                const sel = seleccion === c.cliente_id;
                                return (
                                    <tr
                                        key={c.cliente_id}
                                        tabIndex={0}
                                        onClick={() => abrir(c.cliente_id)}
                                        onKeyDown={(e) => e.key === 'Enter' && abrir(c.cliente_id)}
                                        aria-selected={sel}
                                        className={clsx(
                                            'group cursor-pointer border-b border-border last:border-0 focus-visible:bg-slate-50 focus-visible:outline-none',
                                            sel ? 'bg-slate-50 shadow-[inset_3px_0_0_var(--color-ibero-orange)]' : 'hover:bg-slate-50',
                                        )}
                                    >
                                        <td className="px-4 py-3">
                                            <p className="font-medium">{c.cliente}</p>
                                            <p className="text-xs text-muted-foreground tabular-nums">{c.cliente_id}</p>
                                        </td>
                                        <td className="px-4 py-3">
                                            <span className="inline-flex rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium whitespace-nowrap text-slate-700">{etiquetaTipo(c.tipo_cliente)}</span>
                                        </td>
                                        <td className={clsx('px-4 py-3 text-center tabular-nums', c.responsables === 0 && 'text-amber-700')}>{c.responsables}</td>
                                        <td className="px-4 py-3 text-right tabular-nums whitespace-nowrap">{money(c.venta_total)}</td>
                                        <td className="px-4 py-3">
                                            <EtiquetaEstadoCliente estado={c.estado} />
                                        </td>
                                        <td className={clsx('pr-3', sel ? 'text-slate-500' : 'text-slate-300 group-hover:text-slate-500')}>
                                            <ChevronRight className="size-4" />
                                        </td>
                                    </tr>
                                );
                            })}
                            {lista && lista.rows.length === 0 && (
                                <tr>
                                    <td colSpan={6} className="px-4 py-12 text-center">
                                        <p className="font-medium">Ningún cliente coincide con esa búsqueda</p>
                                        <p className="mt-1 text-sm text-muted-foreground">Prueba con otro código o nombre, o quita algún filtro.</p>
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>

                <Paginacion pagina={filters.pagina} total={total} porPagina={pageSize} onChange={(n) => apply({ pagina: n })} />
            </div>

            {/* Configuración del cliente: panel que se desliza desde la derecha. */}
            <Sheet open={seleccion !== ''} onOpenChange={(o) => !o && cerrarPanel()}>
                <SheetContent className="w-full gap-0 overflow-y-auto bg-white p-0 sm:max-w-lg">
                    <SheetHeader className="border-b border-border px-5 py-4 pr-12">
                        {cabecera ? (
                            <>
                                <p className="text-xs text-muted-foreground tabular-nums">{cabecera.cliente_id}</p>
                                <SheetTitle className="text-lg font-bold tracking-tight">{cabecera.cliente}</SheetTitle>
                            </>
                        ) : (
                            <SheetTitle className="text-lg font-bold tracking-tight">Cliente {seleccion}</SheetTitle>
                        )}
                        <SheetDescription className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
                            {filaSel && <EtiquetaEstadoCliente estado={filaSel.estado} />}
                            <span>
                                Sugerencia SAP: <span className="font-medium text-foreground">{cabecera?.tipo_sugerido ? etiquetaTipo(cabecera.tipo_sugerido) : '—'}</span>
                            </span>
                        </SheetDescription>
                    </SheetHeader>

                    {!det ? (
                        <div className="space-y-4 p-5" aria-busy="true" aria-label="Cargando cliente">
                            <Skeleton className="h-4 w-32" />
                            <Skeleton className="h-9 w-full" />
                            <Skeleton className="h-9 w-full" />
                            <Skeleton className="h-16 w-full" />
                            <Skeleton className="mt-6 h-4 w-32" />
                            <Skeleton className="h-12 w-full" />
                        </div>
                    ) : (
                        <>
                            <Seccion titulo="Clasificación" ayuda="Tipo de cliente con el que aparece en los reportes.">
                                <form
                                    className="space-y-4"
                                    onSubmit={(e) => {
                                        e.preventDefault();
                                        router.put(`/admin/clientes/${det.cliente.cliente_id}`, cfg, opts);
                                    }}
                                >
                                    <div>
                                        <label htmlFor="cfg-tipo" className={etiqueta}>
                                            Tipo de cliente
                                        </label>
                                        <SelectBuscable id="cfg-tipo" value={cfg.tipo_cliente} onChange={(v) => setCfg({ ...cfg, tipo_cliente: v })} options={tipos.map((t) => ({ value: t, label: etiquetaTipo(t) }))} buscarPlaceholder="Buscar tipo…" />
                                    </div>
                                    <div>
                                        <span className={etiqueta}>Estado</span>
                                        <div className="inline-flex rounded-lg bg-slate-100 p-1" role="radiogroup" aria-label="Estado del cliente">
                                            {[
                                                [true, 'Activo'],
                                                [false, 'Inactivo'],
                                            ].map(([v, l]) => (
                                                <button
                                                    key={String(l)}
                                                    type="button"
                                                    role="radio"
                                                    aria-checked={cfg.activo === v}
                                                    onClick={() => setCfg({ ...cfg, activo: v as boolean })}
                                                    className={clsx('flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm transition-colors', cfg.activo === v ? 'bg-white font-semibold shadow-sm' : 'text-muted-foreground hover:text-foreground')}
                                                >
                                                    <span className={clsx('size-1.5 rounded-full', v ? 'bg-emerald-600' : 'bg-slate-400')} />
                                                    {l}
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                    <div>
                                        <label htmlFor="cfg-obs" className={etiqueta}>
                                            Observación <span className="font-normal text-muted-foreground">(opcional)</span>
                                        </label>
                                        <textarea
                                            id="cfg-obs"
                                            value={cfg.observacion}
                                            onChange={(e) => setCfg({ ...cfg, observacion: e.target.value })}
                                            rows={2}
                                            className="block w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
                                        />
                                    </div>
                                    <div className="flex justify-end">
                                        <Button type="submit">Guardar clasificación</Button>
                                    </div>
                                </form>
                            </Seccion>

                            <Seccion titulo="Responsables" ayuda="Vendedor responsable del cliente en cada equipo / grupo.">
                                <ul className="mb-5 space-y-2">
                                    {det.responsables.map((r) => (
                                        <li key={r.id} className="flex items-center justify-between gap-3 rounded-lg bg-slate-50 px-3 py-2">
                                            <div className="min-w-0">
                                                <p className="truncate text-sm font-medium">{r.vendedor}</p>
                                                <p className="text-xs text-muted-foreground">
                                                    <span className="font-medium text-slate-700">{r.grupo === 'TODOS' ? 'Todos los grupos' : r.grupo}</span> · {r.codigo_vendedor} · {r.zona}
                                                </p>
                                            </div>
                                            <button type="button" onClick={() => setQuitar(r)} className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-red-50 hover:text-red-600" aria-label={`Quitar a ${r.vendedor}`}>
                                                <X className="size-4" />
                                            </button>
                                        </li>
                                    ))}
                                    {det.responsables.length === 0 && <li className="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">Sin responsables asignados.</li>}
                                </ul>

                                <form
                                    className="rounded-lg border border-border p-4"
                                    onSubmit={(e) => {
                                        e.preventDefault();
                                        if (!resp.codigo_vendedor) return;
                                        router.post(`/admin/clientes/${det.cliente.cliente_id}/responsables`, resp, { ...opts, onSuccess: () => setResp({ grupo: 'TODOS', codigo_vendedor: '', zona: '' }) });
                                    }}
                                >
                                    <p className="mb-3 text-sm font-semibold">Asignar responsable</p>
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        <div>
                                            <label htmlFor="resp-grupo" className={etiqueta}>
                                                Grupo
                                            </label>
                                            <SelectBuscable id="resp-grupo" value={resp.grupo} onChange={(g) => setResp({ ...resp, grupo: g })} options={opcionesGrupo(lista?.grupos ?? [])} buscarPlaceholder="Buscar grupo…" />
                                        </div>
                                        <div>
                                            <label htmlFor="resp-zona" className={etiqueta}>
                                                Zona
                                            </label>
                                            <Input id="resp-zona" value={resp.zona} onChange={(e) => setResp({ ...resp, zona: e.target.value })} placeholder="La del vendedor" />
                                        </div>
                                        <div className="sm:col-span-2">
                                            <label htmlFor="resp-vendedor" className={etiqueta}>
                                                Vendedor
                                            </label>
                                            <SelectBuscable
                                                id="resp-vendedor"
                                                value={resp.codigo_vendedor}
                                                onChange={(codigo) => setResp({ ...resp, codigo_vendedor: codigo, zona: lista?.vendedores.find((x) => x.codigo_vendedor === codigo)?.zona ?? '' })}
                                                options={opcionesVendedor(lista?.vendedores ?? [])}
                                                placeholder="Elige un vendedor"
                                                buscarPlaceholder="Buscar código, nombre o zona…"
                                            />
                                        </div>
                                    </div>
                                    <div className="mt-4 flex items-center justify-end gap-3">
                                        {!resp.codigo_vendedor && <span className="text-xs text-muted-foreground">Elige un vendedor para asignar.</span>}
                                        <Button type="submit" disabled={!resp.codigo_vendedor}>
                                            <Plus className="size-4" /> Asignar
                                        </Button>
                                    </div>
                                </form>
                            </Seccion>
                        </>
                    )}
                </SheetContent>
            </Sheet>

            {lista && <Sustituir lista={lista} abierto={sustituir} onClose={() => setSustituir(false)} />}

            {/* Confirmar importación. */}
            <Dialog open={archivo !== null} onOpenChange={(o) => !o && setArchivo(null)}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>¿Importar la configuración de clientes?</DialogTitle>
                        <DialogDescription>
                            Se leerá la hoja <strong className="text-foreground">MAESTRO_CLIENTES</strong> de <strong className="text-foreground">{archivo?.name}</strong> y se actualizarán la clasificación y los responsables de los clientes que contenga.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setArchivo(null)}>
                            Cancelar
                        </Button>
                        <Button
                            onClick={() => {
                                const f = archivo;
                                setArchivo(null);
                                if (f) importarArchivo(f, setMsg).catch((x) => setMsg(x instanceof Error ? x.message : 'Error al importar.'));
                            }}
                        >
                            Sí, importar
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Confirmar quitar responsable. */}
            <Dialog open={quitar !== null} onOpenChange={(o) => !o && !guardando && setQuitar(null)}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>¿Quitar a {quitar?.vendedor} como responsable?</DialogTitle>
                        <DialogDescription>
                            Dejará de ser responsable de <strong className="text-foreground">{detalle?.cliente.cliente}</strong> en el grupo <strong className="text-foreground">{quitar?.grupo}</strong>.
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button variant="outline" disabled={guardando} onClick={() => setQuitar(null)}>
                            Cancelar
                        </Button>
                        <Button
                            variant="destructive"
                            disabled={guardando}
                            onClick={() =>
                                quitar &&
                                router.delete(`/admin/clientes/responsables/${quitar.id}`, {
                                    ...opts,
                                    onStart: () => setGuardando(true),
                                    onFinish: () => {
                                        setGuardando(false);
                                        setQuitar(null);
                                    },
                                })
                            }
                        >
                            {guardando ? 'Quitando…' : 'Sí, quitar'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
