import { Head, router } from '@inertiajs/react';
import { AlertTriangle, BadgeDollarSign, FileUp, Layers, Percent, Search, Target, TrendingDown, TrendingUp, Undo2, UserRound, Wallet } from 'lucide-react';
import { Bar, BarChart, CartesianGrid, Cell, LabelList, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import clsx from 'clsx';
import { useMemo, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { DateRange, ErrorBox, FilterSelect, INK, KpiCard, Panel, UpdatedBadge, tooltipStyle } from '@/components/dashboard';
import { CargarCobros } from '@/components/CargarCobros';
import { fecha, int, money, moneyShort, pct, toNum } from '@/lib/format';

type Filters = { desde: string; hasta: string; zona: string; participante: string; grupo: string };
type Num = number | string;
type Part = {
    code: string; name: string; role: string; zone: string; participantType: string; status: string;
    budget: Num; grossSales: Num; returns: Num; netSales: Num; compliance: Num; baseCommission: Num; commissionSales: Num; commissionCollections: Num; commission: Num;
    collectionTarget: Num; collectionActual: Num; collectionCompliance: Num;
};
type Agg = { group?: string; zone?: string; type?: string; budget: Num; netSales: Num; grossSales?: Num; returns?: Num; compliance: Num };
type Prod = { productId: string; product: string; group: string; budget: Num; netSales: Num; compliance: Num };
type Inc = { id: number; type: string; severity: string; zone: string; group: string; seller: string; sellerCode: string; product: string; productId: string; amount: Num; status: string };

type Props = {
    filters: Filters;
    puedeCargarCobros: boolean;
    error: string | null;
    data: {
        kpis: { budget?: Num; grossSales?: Num; returns?: Num; netSales?: Num; compliance?: Num; commission?: Num; sellers?: Num; products?: Num };
        participants: Part[];
        byGroup: Agg[];
        byZone: Agg[];
        topProducts: Prod[];
        incidents: Inc[];
        collections: { loaded?: boolean; collectedTotal?: Num; targetTotal?: Num };
        catalogs: { zones?: string[]; groups?: string[]; participants?: { label: string; value: string }[] };
        updatedAt?: string;
    } | null;
};

type Tab = 'vendedores' | 'jerarquias' | 'grupos' | 'zonas' | 'productos' | 'incidencias';

function Pill({ v }: { v: unknown }) {
    const p = toNum(v) * 100;
    return <span className={clsx('rounded-full px-2 py-0.5 text-[10px] font-bold', p >= 100 ? 'bg-green-50 text-[#006300]' : p >= 80 ? 'bg-amber-50 text-amber-700' : 'bg-red-50 text-[#d03b3b]')}>{pct(p)}</span>;
}

export default function ComisionesVendedores({ filters, puedeCargarCobros, error, data }: Props) {
    const k = data?.kpis ?? {};
    const apply = (patch: Partial<Filters>) => router.get('/comisiones-vendedores', { ...filters, ...patch }, { preserveState: true, preserveScroll: true });
    const [buscar, setBuscar] = useState('');
    const [tab, setTab] = useState<Tab>('vendedores');
    const [sel, setSel] = useState<string | null>(null);
    const [cobros, setCobros] = useState(false);

    const filtrar = <T,>(xs: T[], texto: (x: T) => string) => {
        const t = buscar.trim().toLowerCase();
        return t ? xs.filter((x) => texto(x).toLowerCase().includes(t)) : xs;
    };
    const parts = data?.participants ?? [];
    const vendedores = filtrar(parts.filter((p) => p.participantType === 'VENDEDOR'), (p) => `${p.code} ${p.name} ${p.zone} ${p.role}`);
    const jerarquias = filtrar(parts.filter((p) => p.participantType !== 'VENDEDOR'), (p) => `${p.code} ${p.name} ${p.zone} ${p.role}`);
    const top = useMemo(() => [...vendedores].sort((a, b) => toNum(b.netSales) - toNum(a.netSales)).slice(0, 12).map((p) => ({ ...p, venta: toNum(p.netSales), c: toNum(p.compliance) })), [vendedores]);
    const elegido = parts.find((p) => p.code === sel) ?? parts[0];
    const gap = toNum(k.budget) - toNum(k.netSales);

    const tabs: [Tab, string, number][] = [
        ['vendedores', 'Vendedores', vendedores.length],
        ['jerarquias', 'Jerarquías', jerarquias.length],
        ['grupos', 'Grupos', data?.byGroup.length ?? 0],
        ['zonas', 'Zonas', data?.byZone.length ?? 0],
        ['productos', 'Productos', data?.topProducts.length ?? 0],
        ['incidencias', 'Incidencias', data?.incidents.length ?? 0],
    ];

    const TablaParticipantes = ({ filas }: { filas: Part[] }) => (
        <table className="w-full min-w-[1200px] text-[11px] tabular-nums">
            <thead className="sticky top-0 bg-slate-800 text-[10px] tracking-wider text-white uppercase">
                <tr>
                    {['Código', 'Participante', 'Zona / tipo', 'Presupuesto', 'Venta neta', 'Cumplimiento', 'Faltante / superávit', 'Cobros', 'Base', 'Com. ventas', 'Com. cobros', 'Comisión total', 'Estado'].map((h, i) => (
                        <th key={h} className={clsx('px-2 py-2', i >= 3 && i !== 12 ? 'text-right' : 'text-left')}>
                            {h}
                        </th>
                    ))}
                </tr>
            </thead>
            <tbody>
                {filas.map((p) => {
                    const dif = toNum(p.netSales) - toNum(p.budget);
                    return (
                        <tr key={`${p.code}-${p.role}`} onClick={() => setSel(p.code)} className={clsx('cursor-pointer border-t border-slate-100 hover:bg-slate-50', sel === p.code && 'bg-indigo-50/50')}>
                            <td className="px-2 py-1.5 font-semibold text-brand">{p.code}</td>
                            <td className="px-2">
                                <span className="block font-bold">{p.name}</span>
                                <span className="text-[10px] text-slate-400">{p.role}</span>
                            </td>
                            <td className="px-2">
                                {p.zone}
                                <span className="block text-[9px] text-brand uppercase">{p.participantType}</span>
                            </td>
                            <td className="px-2 text-right">{money(p.budget)}</td>
                            <td className="px-2 text-right font-bold text-emerald-700">{money(p.netSales)}</td>
                            <td className="px-2 text-right">
                                <Pill v={p.compliance} />
                            </td>
                            <td className={clsx('px-2 text-right font-semibold', dif >= 0 ? 'text-[#006300]' : 'text-orange-600')}>
                                {dif >= 0 ? '+' : ''}
                                {money(dif)}
                            </td>
                            <td className="px-2 text-right">{toNum(p.collectionTarget) > 0 ? pct(toNum(p.collectionCompliance) * 100) : <span className="rounded bg-amber-50 px-1.5 text-[9px] font-bold text-amber-700">PENDIENTE</span>}</td>
                            <td className="px-2 text-right">{money(p.baseCommission)}</td>
                            <td className="px-2 text-right text-brand">{money(p.commissionSales)}</td>
                            <td className="px-2 text-right">{toNum(p.commissionCollections) ? money(p.commissionCollections) : '—'}</td>
                            <td className="px-2 text-right font-bold">{money(p.commission)}</td>
                            <td className="px-2">
                                <span className="rounded bg-amber-50 px-1.5 py-0.5 text-[9px] font-bold text-amber-700">{p.status}</span>
                            </td>
                        </tr>
                    );
                })}
            </tbody>
        </table>
    );

    const TablaAgg = ({ filas, clave }: { filas: Agg[]; clave: 'group' | 'zone' }) => (
        <table className="w-full text-[11px] tabular-nums">
            <thead className="bg-slate-800 text-[10px] tracking-wider text-white uppercase">
                <tr>
                    <th className="px-2 py-2 text-left">{clave === 'group' ? 'Grupo' : 'Zona'}</th>
                    <th className="px-2 text-right">Presupuesto</th>
                    {clave === 'group' && <th className="px-2 text-right">Venta bruta</th>}
                    {clave === 'group' && <th className="px-2 text-right">Devoluciones</th>}
                    <th className="px-2 text-right">Venta neta</th>
                    <th className="px-2 text-right">Cumplimiento</th>
                </tr>
            </thead>
            <tbody>
                {filas.map((r) => (
                    <tr key={r[clave]} className="border-t border-slate-100">
                        <td className="px-2 py-1.5 font-bold">{r[clave]}</td>
                        <td className="px-2 text-right">{money(r.budget)}</td>
                        {clave === 'group' && <td className="px-2 text-right">{money(r.grossSales)}</td>}
                        {clave === 'group' && <td className="px-2 text-right">{money(r.returns)}</td>}
                        <td className="px-2 text-right font-bold text-emerald-700">{money(r.netSales)}</td>
                        <td className="px-2 text-right">
                            <Pill v={r.compliance} />
                        </td>
                    </tr>
                ))}
            </tbody>
        </table>
    );

    return (
        <AppLayout>
            <Head title="Comisiones Vendedores" />

            <header className="mb-5">
                <h1 className="text-3xl font-extrabold tracking-tight">Comisiones Vendedores</h1>
                <p className="mt-1 text-sm text-slate-500">
                    Presupuesto, ventas netas, cobros y comisión por participante ·{' '}
                    <b className="text-brand">
                        {fecha(filters.desde)} a {fecha(filters.hasta)}
                    </b>
                    <UpdatedBadge at={data?.updatedAt} />
                </p>
            </header>

            <div className="mb-5 flex flex-wrap items-stretch gap-2">
                {puedeCargarCobros && (
                    <button type="button" onClick={() => setCobros(true)} className="flex items-center gap-2 rounded-xl border border-cyan-200 bg-cyan-50 px-4 text-xs font-bold text-cyan-800 uppercase hover:bg-cyan-100">
                        <FileUp className="size-4" /> Cargar cobros
                    </button>
                )}
                <DateRange desde={filters.desde} hasta={filters.hasta} onChange={apply} />
                <FilterSelect multiple label="Zona" value={filters.zona} all="TODOS" options={data?.catalogs.zones ?? []} onChange={(v) => apply({ zona: v })} />
                <label className="flex min-w-56 flex-col rounded-xl border border-slate-200 bg-white px-3 py-1.5">
                    <span className="text-[10px] font-semibold tracking-wider text-slate-400 uppercase">Persona</span>
                    <select value={filters.participante} onChange={(e) => apply({ participante: e.target.value })} className="bg-transparent text-xs font-semibold text-brand outline-none">
                        <option value="TODOS">Todas las personas</option>
                        {(data?.catalogs.participants ?? []).map((p) => (
                            <option key={p.value} value={p.value}>
                                {p.value} · {p.label}
                            </option>
                        ))}
                    </select>
                </label>
                <FilterSelect multiple label="Grupo" value={filters.grupo} all="TODOS" options={data?.catalogs.groups ?? []} onChange={(v) => apply({ grupo: v })} />
                <div className="relative flex min-w-60 items-center">
                    <Search className="absolute left-3 size-4 text-slate-400" />
                    <input value={buscar} onChange={(e) => setBuscar(e.target.value)} placeholder="Buscar vendedor, código, zona o perfil" className="h-full w-full rounded-xl border border-slate-200 bg-white py-2 pr-3 pl-9 text-xs outline-none focus:border-brand" />
                </div>
            </div>

            {error || !data ? (
                <ErrorBox message={error ?? 'No fue posible cargar Comisiones Vendedores.'} />
            ) : (
                <>
                    <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">{money(k.budget)}</p>
                            <p className="text-[11px] text-slate-400">
                                {int(k.sellers)} participantes · {int(k.products)} productos
                            </p>
                        </KpiCard>
                        <KpiCard title="Venta bruta" icon={<TrendingUp className="size-4" />} accent="#06b6d4">
                            <p className="text-base font-extrabold">{money(k.grossSales)}</p>
                            <p className="text-[11px] text-slate-400">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">Descontadas para la venta neta</p>
                        </KpiCard>
                        <KpiCard title="Venta neta" icon={<Wallet className="size-4" />} accent="#10b981">
                            <p className="text-base font-extrabold">{money(k.netSales)}</p>
                            <p className="text-[11px] text-slate-400">Venta bruta menos devoluciones</p>
                        </KpiCard>
                        <KpiCard title="Cumplimiento" icon={<Percent className="size-4" />} accent="#f97316">
                            <p className="text-base font-extrabold">{pct(toNum(k.compliance) * 100)}</p>
                            <div className="mt-1 h-1.5 rounded-full bg-slate-100">
                                <div className="h-1.5 rounded-full bg-brand" style={{ width: `${Math.min(100, toNum(k.compliance) * 100)}%` }} />
                            </div>
                        </KpiCard>
                        <KpiCard title={gap > 0 ? 'Faltante' : 'Superávit'} icon={<TrendingDown className="size-4" />} accent="#f59e0b">
                            <p className="text-base font-extrabold">{money(Math.abs(gap))}</p>
                            <p className="text-[11px] text-slate-400">Contra el presupuesto del periodo</p>
                        </KpiCard>
                        <KpiCard title="Cobros" icon={<BadgeDollarSign className="size-4" />} accent="#f59e0b">
                            <p className="text-base font-extrabold">{data.collections.loaded ? money(data.collections.collectedTotal) : 'PENDIENTES'}</p>
                            <p className="text-[11px] text-slate-400">{data.collections.loaded ? `Meta ${money(data.collections.targetTotal)}` : 'Archivo mensual de RH'}</p>
                        </KpiCard>
                        <KpiCard title="Comisión total" icon={<BadgeDollarSign className="size-4" />} accent="#8b5cf6">
                            <p className="text-base font-extrabold">{money(k.commission)}</p>
                            <p className="text-[11px] text-slate-400">Ventas + cobros</p>
                        </KpiCard>
                    </div>

                    <div className="mb-5 grid grid-cols-1 gap-4 xl:grid-cols-[2.2fr_1fr]">
                        <Panel title="Venta neta y cumplimiento por vendedor" icon={<TrendingUp className="size-4" />} accent="#5b4ce6" right={`${top.length} vendedores · etiqueta: cumplimiento`}>
                            <div className="h-80">
                                <ResponsiveContainer width="100%" height="100%">
                                    <BarChart data={top} margin={{ top: 24, right: 8, left: 0, bottom: 44 }}>
                                        <CartesianGrid vertical={false} stroke={INK.grid} />
                                        <XAxis dataKey="name" interval={0} angle={-25} textAnchor="end" tickLine={false} axisLine={{ stroke: INK.axis }} tick={{ fill: INK.muted, fontSize: 10 }} tickFormatter={(v: string) => v.split(' ').slice(0, 2).join(' ')} />
                                        <YAxis tickLine={false} axisLine={false} width={70} tick={{ fill: INK.muted, fontSize: 11 }} tickFormatter={(v) => moneyShort(v)} />
                                        <Tooltip formatter={(v, _n, p) => [`${money(v)} · cumpl. ${pct((p.payload as { c: number }).c * 100)}`, 'Venta neta']} contentStyle={tooltipStyle} cursor={{ fill: 'rgba(91,76,230,0.06)' }} />
                                        <Bar dataKey="venta" radius={[4, 4, 0, 0]} maxBarSize={44} cursor="pointer" onClick={(d) => setSel((d as unknown as Part).code)}>
                                            {top.map((p) => (
                                                <Cell key={p.code} fill={elegido?.code === p.code ? '#047857' : '#10b981'} />
                                            ))}
                                            <LabelList dataKey="c" position="top" formatter={(v) => pct(toNum(v) * 100)} style={{ fill: INK.secondary, fontSize: 10, fontWeight: 700 }} />
                                        </Bar>
                                    </BarChart>
                                </ResponsiveContainer>
                            </div>
                        </Panel>

                        <Panel title="Detalle seleccionado" icon={<UserRound className="size-4" />} accent="#06b6d4" right="Clic en una barra o fila">
                            {elegido && (
                                <>
                                    <div className="mb-3 rounded-xl bg-ibero-navy p-3 text-white">
                                        <div className="flex items-start justify-between">
                                            <div>
                                                <p className="font-extrabold">{elegido.name}</p>
                                                <p className="text-[11px] text-slate-300">
                                                    {elegido.code} · {elegido.zone} · {elegido.participantType}
                                                </p>
                                            </div>
                                            <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[9px] font-bold text-amber-800">{elegido.status}</span>
                                        </div>
                                        <p className="mt-2 text-[10px] text-slate-400 uppercase">Comisión total</p>
                                        <p className="text-2xl font-extrabold">{money(elegido.commission)}</p>
                                    </div>
                                    <div className="grid grid-cols-2 gap-2 text-xs">
                                        {(
                                            [
                                                ['Presupuesto', money(elegido.budget)],
                                                ['Venta neta', money(elegido.netSales)],
                                                ['Cumplimiento', pct(toNum(elegido.compliance) * 100)],
                                                ['Faltante', money(Math.max(0, toNum(elegido.budget) - toNum(elegido.netSales)))],
                                                ['Base de comisión', money(elegido.baseCommission)],
                                                ['Com. ventas / cobros', `${moneyShort(elegido.commissionSales)} / ${moneyShort(elegido.commissionCollections)}`],
                                            ] as [string, string][]
                                        ).map(([l, v]) => (
                                            <div key={l} className="rounded-xl border border-slate-100 p-2.5">
                                                <p className="text-[10px] font-semibold tracking-wider text-slate-400 uppercase">{l}</p>
                                                <p className="font-bold">{v}</p>
                                            </div>
                                        ))}
                                    </div>
                                </>
                            )}
                        </Panel>
                    </div>

                    <Panel
                        title="Detalle del dashboard"
                        icon={<Layers className="size-4" />}
                        accent="#6366f1"
                        right={
                            <span className="inline-flex flex-wrap gap-1">
                                {tabs.map(([t, l, n]) => (
                                    <button key={t} type="button" onClick={() => setTab(t)} className={clsx('rounded-lg px-3 py-1 text-[10px] font-bold uppercase', tab === t ? 'bg-brand text-white' : 'bg-slate-100 text-slate-500')}>
                                        {l} {n}
                                    </button>
                                ))}
                            </span>
                        }
                    >
                        <div className="max-h-[30rem] overflow-auto">
                            {tab === 'vendedores' && <TablaParticipantes filas={vendedores} />}
                            {tab === 'jerarquias' && <TablaParticipantes filas={jerarquias} />}
                            {tab === 'grupos' && <TablaAgg filas={data.byGroup} clave="group" />}
                            {tab === 'zonas' && <TablaAgg filas={data.byZone} clave="zone" />}
                            {tab === 'productos' && (
                                <table className="w-full 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">Producto</th>
                                            <th className="px-2 text-left">Grupo</th>
                                            <th className="px-2 text-right">Presupuesto</th>
                                            <th className="px-2 text-right">Venta neta</th>
                                            <th className="px-2 text-right">Cumplimiento</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {filtrar(data.topProducts, (p) => `${p.productId} ${p.product} ${p.group}`).map((p) => (
                                            <tr key={p.productId} className="border-t border-slate-100">
                                                <td className="px-2 py-1.5">
                                                    <span className="block font-bold">{p.product}</span>
                                                    <span className="text-[10px] text-slate-400">{p.productId}</span>
                                                </td>
                                                <td className="px-2">{p.group}</td>
                                                <td className="px-2 text-right">{money(p.budget)}</td>
                                                <td className="px-2 text-right font-bold text-emerald-700">{money(p.netSales)}</td>
                                                <td className="px-2 text-right">
                                                    <Pill v={p.compliance} />
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                            {tab === 'incidencias' && (
                                <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>
                                            {['Tipo', 'Severidad', 'Vendedor', 'Zona', 'Grupo', 'Producto', 'Monto', 'Estado'].map((h, i) => (
                                                <th key={h} className={clsx('px-2 py-2', i === 6 ? 'text-right' : 'text-left')}>
                                                    {h}
                                                </th>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {filtrar(data.incidents, (x) => `${x.type} ${x.seller} ${x.sellerCode} ${x.product} ${x.productId} ${x.zone}`).map((x) => (
                                            <tr key={x.id} className="border-t border-slate-100">
                                                <td className="px-2 py-1.5 font-semibold">{x.type.replaceAll('_', ' ')}</td>
                                                <td className="px-2">
                                                    <span className="inline-flex items-center gap-1 text-amber-700">
                                                        <AlertTriangle className="size-3" /> {x.severity}
                                                    </span>
                                                </td>
                                                <td className="px-2">
                                                    {x.seller} <span className="text-[10px] text-brand">{x.sellerCode}</span>
                                                </td>
                                                <td className="px-2">{x.zone}</td>
                                                <td className="px-2">{x.group}</td>
                                                <td className="px-2">
                                                    {x.product} <span className="text-[10px] text-slate-400">{x.productId}</span>
                                                </td>
                                                <td className="px-2 text-right">{money(x.amount)}</td>
                                                <td className="px-2">{x.status}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </div>
                    </Panel>
                </>
            )}

            {cobros && <CargarCobros mesPorDefecto={`${filters.desde.slice(0, 7)}-01`} onClose={() => setCobros(false)} />}
        </AppLayout>
    );
}
