import { Head, router } from '@inertiajs/react';
import { CalendarDays, ListTree, Search, Table2, Target, TrendingDown, TrendingUp, Undo2, Users, Wallet } from 'lucide-react';
import clsx from 'clsx';
import { Fragment, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { DateRange, ErrorBox, KpiCard, Panel, Toggle, UpdatedBadge } from '@/components/dashboard';
import { MultiSelect, joinPipe, splitPipe, type MultiOption } from '@/components/MultiSelect';
import { fecha, int, money, moneyShort, pct, toNum } from '@/lib/format';

type Filters = { desde: string; hasta: string; visual: string; zonas: string; grupos: string; lineas: string; vendedores: string };
type Num = number | string;
type Fila = { id: string; nombre: string; grupo: string; linea: string; vendedor?: string; presupuesto: number; neta: number; devoluciones: number; cumplimiento: number | null };
type Vendedor = { codigo: string; nombre: string; presupuesto: number; bruta: number; devoluciones: number; neta: number; cumplimiento: number | null };

type Props = {
    filters: Filters;
    error: string | null;
    resumen: {
        kpis: { budgetSales?: Num; budgetUnits?: Num; grossSales?: Num; returns?: Num; netSales?: Num; units?: Num; compliance?: Num; gap?: Num; sellers?: Num; products?: Num; budget?: Num; updatedAt?: string };
        businessDays?: number;
        rangeDays?: number;
        opciones: { zonas: string[]; grupos: string[]; lineas: string[]; vendedores: MultiOption[] };
    } | null;
    lineaZona: { linea: string; z1p: number; z1v: number; z2p: number; z2v: number }[];
    grupos: { grupo: string; presupuesto: number; bruta: number; devoluciones: number; neta: number; cumplimiento: number | null; vendedores: Vendedor[] }[];
    productos: Fila[];
    lineas: Fila[];
    vendedores: Fila[];
    productosVendedor?: { rows: Fila[]; page: number; total: number; pages: number };
    ciudades?: { city: string; province: string; zone: string; grossSales: Num; units: Num; clients: Num; records: Num }[];
};

const COLOR_GRUPO: Record<string, string> = { OTC: 'bg-lime-100', ETICOS: 'bg-orange-100', GENERICOS: 'bg-sky-100', MAQUILA: 'bg-violet-100' };
const opts = (xs: string[]) => xs.map((x) => ({ value: x, label: x }));

function Logro({ v }: { v: number | null }) {
    if (v === null || !Number.isFinite(v)) return <span className="text-slate-300">—</span>;
    const p = v * 100;
    return <span className={clsx('font-bold', p >= 100 ? 'text-[#006300]' : p >= 50 ? 'text-amber-600' : 'text-[#d03b3b]')}>{pct(p)}</span>;
}

type Tab = 'productos' | 'lineas' | 'vendedores' | 'pv' | 'ciudades';

export default function CumplimientoVendedores(props: Props) {
    const { filters, error, resumen, lineaZona, grupos } = props;
    const u = filters.visual === 'UNIDADES';
    const k = resumen?.kpis ?? {};
    const fmt = (v: unknown) => (u ? int(v) : money(v));
    const apply = (patch: Partial<Filters>) => router.get('/presupuesto/vendedores', { ...filters, ...patch }, { preserveState: true, preserveScroll: true });

    const presupuesto = toNum(u ? k.budgetUnits : k.budgetSales);
    const neta = toNum(u ? k.units : k.netSales);
    const cumplimiento = toNum(k.compliance) * 100;
    const gap = toNum(k.gap);

    const tot = lineaZona.reduce((a, r) => ({ z1p: a.z1p + r.z1p, z1v: a.z1v + r.z1v, z2p: a.z2p + r.z2p, z2v: a.z2v + r.z2v }), { z1p: 0, z1v: 0, z2p: 0, z2v: 0 });

    const [tab, setTab] = useState<Tab>('productos');
    const [pvBuscar, setPvBuscar] = useState('');
    const cargarPv = (pagina: number, buscar = pvBuscar) => router.reload({ only: ['productosVendedor'], data: { pv_pagina: pagina, pv_buscar: buscar } });
    const abrir = (t: Tab) => {
        setTab(t);
        if (t === 'pv' && !props.productosVendedor) cargarPv(1);
        if (t === 'ciudades' && !props.ciudades) router.reload({ only: ['ciudades'] });
    };

    const tabla: Fila[] = tab === 'productos' ? props.productos : tab === 'lineas' ? props.lineas : tab === 'vendedores' ? props.vendedores : tab === 'pv' ? (props.productosVendedor?.rows ?? []) : [];

    return (
        <AppLayout>
            <Head title="Ventas vs Cumplimiento" />

            <header className="mb-5">
                <h1 className="text-3xl font-extrabold tracking-tight">Ventas vs Cumplimiento</h1>
                <p className="mt-1 text-sm text-slate-500">
                    Presupuesto, venta y cumplimiento del periodo seleccionado ·{' '}
                    <b className="text-brand">
                        {fecha(filters.desde)} → {fecha(filters.hasta)}
                    </b>
                    <UpdatedBadge at={k.updatedAt} />
                </p>
            </header>

            <div className="mb-5 flex flex-wrap items-stretch gap-2">
                <DateRange desde={filters.desde} hasta={filters.hasta} onChange={apply} />
                <MultiSelect label="Grupo producto" allLabel="Todos los grupos" options={opts(resumen?.opciones.grupos ?? [])} value={splitPipe(filters.grupos)} onChange={(v) => apply({ grupos: joinPipe(v) })} />
                <MultiSelect label="Zona" allLabel="Todas las zonas" options={opts(resumen?.opciones.zonas ?? [])} value={splitPipe(filters.zonas)} onChange={(v) => apply({ zonas: joinPipe(v) })} />
                <MultiSelect label="Línea" allLabel="Todas las líneas" options={opts(resumen?.opciones.lineas ?? [])} value={splitPipe(filters.lineas)} onChange={(v) => apply({ lineas: joinPipe(v) })} />
                <MultiSelect label="Vendedor" allLabel="Todos los vendedores" className="min-w-60" options={resumen?.opciones.vendedores ?? []} value={splitPipe(filters.vendedores)} onChange={(v) => apply({ vendedores: joinPipe(v) })} />
                <Toggle
                    value={filters.visual}
                    options={[
                        { value: 'VALORES', label: 'RD$' },
                        { value: 'UNIDADES', label: 'Unidades' },
                    ]}
                    onChange={(v) => apply({ visual: v })}
                />
            </div>

            {error || !resumen ? (
                <ErrorBox message={error ?? 'No se pudo cargar el dashboard.'} />
            ) : (
                <>
                    <div className="mb-5 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4 2xl:grid-cols-8">
                        <KpiCard title="Presupuesto" icon={<Target className="size-4" />} accent="#6366f1">
                            <p className="text-base font-extrabold">{fmt(presupuesto)}</p>
                            <p className="text-[11px] text-slate-400">Presupuesto comercial publicado</p>
                        </KpiCard>
                        <KpiCard title={u ? 'Unidades' : 'Venta bruta'} icon={<TrendingUp className="size-4" />} accent="#10b981">
                            <p className="text-base font-extrabold">{fmt(u ? k.units : k.grossSales)}</p>
                            <p className="text-[11px] text-slate-400">Venta antes de devoluciones</p>
                        </KpiCard>
                        <KpiCard title="Devoluciones" icon={<Undo2 className="size-4" />} accent="#e11d48">
                            <p className="text-base font-extrabold">{money(k.returns)}</p>
                            <p className="text-[11px] text-slate-400">Devoluciones del periodo</p>
                        </KpiCard>
                        <KpiCard title={u ? 'Unidades netas' : 'Venta neta'} icon={<Wallet className="size-4" />} accent="#06b6d4">
                            <p className="text-base font-extrabold">{fmt(neta)}</p>
                            <p className="text-[11px] text-slate-400">Venta bruta menos devoluciones</p>
                        </KpiCard>
                        <KpiCard title="Cumplimiento" icon={<Target className="size-4" />} accent="#f97316">
                            <p className={clsx('text-base font-extrabold', cumplimiento >= 100 ? 'text-[#006300]' : 'text-amber-600')}>{pct(cumplimiento)}</p>
                            <p className="text-[11px] text-slate-400">Venta neta / presupuesto</p>
                        </KpiCard>
                        <KpiCard title={gap <= 0 ? 'Excedente' : 'Faltante'} icon={<TrendingDown className="size-4" />} accent={gap <= 0 ? '#10b981' : '#e11d48'}>
                            <p className="text-base font-extrabold">{fmt(Math.abs(gap))}</p>
                            <p className="text-[11px] text-slate-400">Diferencia contra presupuesto</p>
                        </KpiCard>
                        <KpiCard title="Días hábiles" icon={<CalendarDays className="size-4" />} accent="#f97316">
                            <p className="text-base font-extrabold">{int(resumen.businessDays)}</p>
                            <p className="text-[11px] text-slate-400">{int(resumen.rangeDays)} días calendario</p>
                        </KpiCard>
                        <KpiCard title="Vendedores" icon={<Users className="size-4" />} accent="#8b5cf6">
                            <p className="text-base font-extrabold">{int(k.sellers)}</p>
                            <p className="text-[11px] text-slate-400">{int(k.products)} productos en alcance</p>
                        </KpiCard>
                    </div>

                    {/* Línea × zona */}
                    <Panel title="Ventas y presupuesto por línea y zona" icon={<TrendingUp className="size-4" />} accent="#6366f1" right="Zona 1, Zona 2 y total del periodo" className="mb-5">
                        <div className="overflow-x-auto">
                            <table className="w-full min-w-[1000px] text-[11px] tabular-nums">
                                <thead className="text-[10px] tracking-wider uppercase">
                                    <tr>
                                        <th className="bg-slate-800 px-2 py-2 text-left text-white">Línea</th>
                                        <th className="bg-cyan-50 px-2 text-right">Presupuesto Z1</th>
                                        <th className="bg-cyan-50 px-2 text-right">Ventas Z1</th>
                                        <th className="bg-cyan-50 px-2 text-right">Logrado Z1</th>
                                        <th className="bg-orange-50 px-2 text-right">Presupuesto Z2</th>
                                        <th className="bg-orange-50 px-2 text-right">Ventas Z2</th>
                                        <th className="bg-orange-50 px-2 text-right">Logrado Z2</th>
                                        <th className="bg-indigo-50 px-2 text-right">Presupuesto total</th>
                                        <th className="bg-indigo-50 px-2 text-right">Ventas total</th>
                                        <th className="bg-indigo-50 px-2 text-right">Logrado total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {lineaZona.map((r) => (
                                        <tr key={r.linea} className="border-t border-slate-100">
                                            <td className="px-2 py-1.5 font-bold">{r.linea}</td>
                                            <td className="px-2 text-right">{fmt(r.z1p)}</td>
                                            <td className="px-2 text-right">{fmt(r.z1v)}</td>
                                            <td className="px-2 text-right"><Logro v={r.z1p ? r.z1v / r.z1p : null} /></td>
                                            <td className="px-2 text-right">{fmt(r.z2p)}</td>
                                            <td className="px-2 text-right">{fmt(r.z2v)}</td>
                                            <td className="px-2 text-right"><Logro v={r.z2p ? r.z2v / r.z2p : null} /></td>
                                            <td className="px-2 text-right">{fmt(r.z1p + r.z2p)}</td>
                                            <td className="px-2 text-right font-bold">{fmt(r.z1v + r.z2v)}</td>
                                            <td className="px-2 text-right"><Logro v={r.z1p + r.z2p ? (r.z1v + r.z2v) / (r.z1p + r.z2p) : null} /></td>
                                        </tr>
                                    ))}
                                </tbody>
                                <tfoot className="bg-slate-800 font-bold text-white">
                                    <tr>
                                        <td className="px-2 py-2">TOTAL</td>
                                        <td className="px-2 text-right">{fmt(tot.z1p)}</td>
                                        <td className="px-2 text-right">{fmt(tot.z1v)}</td>
                                        <td className="px-2 text-right">{tot.z1p ? pct((tot.z1v / tot.z1p) * 100, 2) : '—'}</td>
                                        <td className="px-2 text-right">{fmt(tot.z2p)}</td>
                                        <td className="px-2 text-right">{fmt(tot.z2v)}</td>
                                        <td className="px-2 text-right">{tot.z2p ? pct((tot.z2v / tot.z2p) * 100, 2) : '—'}</td>
                                        <td className="px-2 text-right">{fmt(tot.z1p + tot.z2p)}</td>
                                        <td className="px-2 text-right">{fmt(tot.z1v + tot.z2v)}</td>
                                        <td className="px-2 text-right">{tot.z1p + tot.z2p ? pct(((tot.z1v + tot.z2v) / (tot.z1p + tot.z2p)) * 100, 2) : '—'}</td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </Panel>

                    {/* Grupos y vendedores */}
                    <Panel title="Líneas y vendedores" icon={<Users className="size-4" />} accent="#10b981" right="Los renglones de color son el subtotal de cada grupo" className="mb-5">
                        <div className="max-h-[32rem] overflow-auto">
                            <table className="w-full min-w-[900px] text-[11px] tabular-nums">
                                <thead className="sticky top-0 bg-slate-800 text-[10px] tracking-wider text-white uppercase">
                                    <tr>
                                        <th className="px-2 py-2 text-left">Grupo / vendedor</th>
                                        <th className="px-2 text-right">Presupuesto</th>
                                        <th className="px-2 text-right">{u ? 'Unidades' : 'Venta bruta'}</th>
                                        <th className="px-2 text-right">Devoluciones</th>
                                        <th className="px-2 text-right">{u ? 'Unid. netas' : 'Venta neta'}</th>
                                        <th className="px-2 text-right">Cumplimiento</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {grupos.map((g) => (
                                        <Fragment key={g.grupo}>
                                            <tr className={clsx('font-bold', COLOR_GRUPO[g.grupo] ?? 'bg-slate-100')}>
                                                <td className="px-2 py-1.5">PRODUCTOS {g.grupo}</td>
                                                <td className="px-2 text-right">{fmt(g.presupuesto)}</td>
                                                <td className="px-2 text-right">{fmt(g.bruta)}</td>
                                                <td className="px-2 text-right">{u ? '—' : money(g.devoluciones)}</td>
                                                <td className="px-2 text-right">{fmt(g.neta)}</td>
                                                <td className="px-2 text-right"><Logro v={g.cumplimiento} /></td>
                                            </tr>
                                            {g.vendedores.map((s) => (
                                                <tr key={`${g.grupo}-${s.codigo}`} className="border-t border-slate-100">
                                                    <td className="py-1.5 pr-2 pl-5">
                                                        {s.nombre} <span className="text-[10px] font-semibold text-brand">{s.codigo}</span>
                                                    </td>
                                                    <td className="px-2 text-right">{fmt(s.presupuesto)}</td>
                                                    <td className="px-2 text-right">{fmt(s.bruta)}</td>
                                                    <td className="px-2 text-right">{u ? '—' : money(s.devoluciones)}</td>
                                                    <td className="px-2 text-right">{fmt(s.neta)}</td>
                                                    <td className="px-2 text-right"><Logro v={s.cumplimiento} /></td>
                                                </tr>
                                            ))}
                                        </Fragment>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </Panel>

                    {/* Detalle operativo */}
                    <Panel title="Detalle operativo del reporte" icon={<ListTree className="size-4" />} accent="#2a78d6" right="Productos, líneas, vendedores y distribución geográfica">
                        <div className="mb-3 flex flex-wrap gap-1">
                            {(
                                [
                                    ['productos', `Productos ${props.productos.length}`],
                                    ['lineas', `Líneas ${props.lineas.length}`],
                                    ['vendedores', `Vendedores ${props.vendedores.length}`],
                                    ['pv', `Productos x vendedor${props.productosVendedor ? ` ${int(props.productosVendedor.total)}` : ''}`],
                                    ['ciudades', `Provincia / ciudad${props.ciudades ? ` ${props.ciudades.length}` : ''}`],
                                ] as [Tab, string][]
                            ).map(([t, l]) => (
                                <button key={t} type="button" onClick={() => abrir(t)} className={clsx('rounded-lg px-3 py-1.5 text-[11px] font-bold uppercase', tab === t ? 'bg-brand text-white' : 'bg-slate-100 text-slate-500 hover:bg-slate-200')}>
                                    {l}
                                </button>
                            ))}
                        </div>

                        {tab === 'pv' && (
                            <form
                                className="relative mb-2 max-w-sm"
                                onSubmit={(e) => {
                                    e.preventDefault();
                                    cargarPv(1);
                                }}
                            >
                                <Search className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-slate-400" />
                                <input value={pvBuscar} onChange={(e) => setPvBuscar(e.target.value)} placeholder="Buscar producto o vendedor y Enter" className="w-full rounded-lg border border-slate-200 py-1.5 pr-2 pl-7 text-xs outline-none focus:border-brand" />
                            </form>
                        )}

                        {tab === 'ciudades' ? (
                            !props.ciudades ? (
                                <p className="p-4 text-sm text-slate-400">Cargando…</p>
                            ) : (
                                <div className="max-h-[28rem] overflow-auto">
                                    <table className="w-full text-[11px] tabular-nums">
                                        <thead className="sticky top-0 bg-white text-[10px] tracking-wider text-slate-400 uppercase">
                                            <tr>
                                                <th className="py-1.5 text-left">Ciudad</th>
                                                <th className="text-left">Provincia</th>
                                                <th className="text-left">Zona</th>
                                                <th className="text-right">Venta</th>
                                                <th className="text-right">Unidades</th>
                                                <th className="text-right">Clientes</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {props.ciudades.map((c) => (
                                                <tr key={`${c.city}-${c.zone}`} className="border-t border-slate-100">
                                                    <td className="py-1.5 font-semibold">{c.city}</td>
                                                    <td>{c.province}</td>
                                                    <td>{c.zone}</td>
                                                    <td className="text-right font-bold">{money(c.grossSales)}</td>
                                                    <td className="text-right">{int(c.units)}</td>
                                                    <td className="text-right">{int(c.clients)}</td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )
                        ) : tab === 'pv' && !props.productosVendedor ? (
                            <p className="p-4 text-sm text-slate-400">Cargando…</p>
                        ) : (
                            <>
                                <div className="max-h-[28rem] overflow-auto">
                                    <table className="w-full text-[11px] tabular-nums">
                                        <thead className="sticky top-0 bg-white text-[10px] tracking-wider text-slate-400 uppercase">
                                            <tr>
                                                <th className="py-1.5 text-left">{tab === 'lineas' ? 'Línea' : tab === 'vendedores' ? 'Vendedor' : 'SKU / producto'}</th>
                                                {tab === 'pv' && <th className="text-left">Vendedor</th>}
                                                {(tab === 'productos' || tab === 'pv') && <th className="text-left">Grupo</th>}
                                                {tab !== 'lineas' && <th className="text-left">{tab === 'vendedores' ? 'Zona' : 'Línea'}</th>}
                                                <th className="text-right">Presupuesto</th>
                                                <th className="text-right">{u ? 'Unid. netas' : 'Venta neta'}</th>
                                                <th className="text-right">Devol.</th>
                                                <th className="text-right">Cumpl.</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {tabla.map((r, i) => (
                                                <tr key={`${r.id}-${r.vendedor ?? ''}-${i}`} className="border-t border-slate-100">
                                                    <td className="py-1.5">
                                                        <span className="block font-semibold">{r.nombre}</span>
                                                        {r.id !== r.nombre && <span className="text-[10px] text-slate-400">{r.id}</span>}
                                                    </td>
                                                    {tab === 'pv' && <td>{r.vendedor}</td>}
                                                    {(tab === 'productos' || tab === 'pv') && <td>{r.grupo}</td>}
                                                    {tab !== 'lineas' && <td>{r.linea}</td>}
                                                    <td className="text-right">{fmt(r.presupuesto)}</td>
                                                    <td className="text-right font-bold">{fmt(r.neta)}</td>
                                                    <td className="text-right">{moneyShort(r.devoluciones)}</td>
                                                    <td className="text-right">
                                                        <Logro v={r.cumplimiento} />
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                {tab === 'pv' && props.productosVendedor && (
                                    <div className="mt-3 flex items-center justify-between text-xs">
                                        <button type="button" disabled={props.productosVendedor.page <= 1} onClick={() => cargarPv(props.productosVendedor!.page - 1)} className="rounded-lg border border-slate-200 px-3 py-1 disabled:opacity-40">
                                            Anterior
                                        </button>
                                        <span className="text-slate-500">
                                            Página {props.productosVendedor.page} de {props.productosVendedor.pages} · {int(props.productosVendedor.total)} filas
                                        </span>
                                        <button type="button" disabled={props.productosVendedor.page >= props.productosVendedor.pages} onClick={() => cargarPv(props.productosVendedor!.page + 1)} className="rounded-lg border border-slate-200 px-3 py-1 disabled:opacity-40">
                                            Siguiente
                                        </button>
                                    </div>
                                )}
                            </>
                        )}
                        <p className="mt-2 flex items-center gap-1 text-[10px] text-slate-400">
                            <Table2 className="size-3" /> Zona solo actúa como filtro en este detalle.
                        </p>
                    </Panel>
                </>
            )}
        </AppLayout>
    );
}
