import { Head } from '@inertiajs/react';
import { AlertTriangle, BarChart3, CheckCircle2, FileText, Search, ShieldCheck, TrendingDown, XCircle } from 'lucide-react';
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';
import clsx from 'clsx';
import { useMemo, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { KpiCard, Panel, tooltipStyle } from '@/components/dashboard';
import { int, toNum } from '@/lib/format';

type Archivo = {
    nombre_archivo: string; status: string; detalle?: string | null; motivo_fallo?: string | null; ejecuciones?: number; primera_ejecucion?: string; ultima_ejecucion?: string;
    filas_fact?: number; fecha_min?: string | null; fecha_max?: string | null; venta_total?: number | string;
    filas_producto_sin_match?: number; filas_sucursal_sin_match?: number; filas_provincia_null?: number; filas_ciudad_null?: number;
    filas_precio_promedio_cero?: number; filas_venta_cero?: number; filas_dinero_invalido?: number; quality_score?: number | string;
};
type Props = { archivos: Archivo[]; actualizado?: string | null };

const MESES = ['ENE', 'FEB', 'MAR', 'ABR', 'MAY', 'JUN', 'JUL', 'AGO', 'SEP', 'OCT', 'NOV', 'DIC'];
const norm = (v: unknown) => String(v ?? '').trim().toUpperCase();

/* Mismas reglas que la app anterior */
const grupoEstado = (s: string) => {
    const t = norm(s);
    if (t === 'OK') return 'OK';
    if (t === 'ERROR') return 'ERROR';
    if (t === 'SUPERSEDED_MANUAL' || t === 'DELETED_MANUAL') return 'MANUAL';
    return 'OTROS';
};
const problemas = (a: Archivo) => toNum(a.filas_sucursal_sin_match) + toNum(a.filas_provincia_null) + toNum(a.filas_ciudad_null) + toNum(a.filas_precio_promedio_cero) + toNum(a.filas_venta_cero) + toNum(a.filas_dinero_invalido);
const calidad = (a: Archivo) => (grupoEstado(a.status) === 'OK' && problemas(a) === 0 ? 100 : toNum(a.quality_score));
const cadena = (nombre: string) => {
    const t = norm(nombre);
    if (t.includes('CAROL')) return 'CAROL';
    if (t.includes('FARMA VALUE') || t.includes('FARMAVALUE')) return 'FARMAVALUE';
    if (t.includes('FARMA EXTRA') || t.includes('FARMAEXTRA') || t.includes('FARMATRIX')) return 'FARMAEXTRA';
    if (t.includes('GBC') || t.includes('MEDICAR')) return 'GBC';
    if (t.includes('LOS HIDALGOS')) return 'LOS HIDALGOS';
    if (t.includes('UNION')) return 'UNION';
    if (t.includes('FDN') || t.includes('IBERO')) return 'FARMACOS DEL NORTE';
    return 'OTRA CADENA';
};
const mes = (a: Archivo) => (a.fecha_min ? a.fecha_min.slice(0, 7) : 'SIN MES');
const moneyB = (v: unknown) => {
    const n = toNum(v);
    const x = Math.abs(n);
    return x >= 1e9 ? `RD$${(n / 1e9).toFixed(1)}B` : x >= 1e6 ? `RD$${(n / 1e6).toFixed(1)}M` : x >= 1e3 ? `RD$${(n / 1e3).toFixed(0)}K` : `RD$${n.toFixed(0)}`;
};

const INCIDENCIAS: [string, string, (a: Archivo) => number][] = [
    ['SUCURSAL', 'Sucursal no reconocida', (a) => toNum(a.filas_sucursal_sin_match)],
    ['PRODUCTO', 'Producto pendiente catálogo', (a) => toNum(a.filas_producto_sin_match)],
    ['PROVINCIA', 'Sin provincia', (a) => toNum(a.filas_provincia_null)],
    ['CIUDAD', 'Sin ciudad', (a) => toNum(a.filas_ciudad_null)],
    ['PRECIO', 'Precio cero', (a) => toNum(a.filas_precio_promedio_cero)],
    ['VENTA', 'Venta cero', (a) => toNum(a.filas_venta_cero)],
    ['DINERO', 'Dinero inválido', (a) => toNum(a.filas_dinero_invalido)],
];
const COLOR_ESTADO: Record<string, string> = { OK: '#10b981', ERROR: '#ef4444', MANUAL: '#f59e0b', OTROS: '#64748b' };

function Barras({ items, color }: { items: { label: string; sub?: string; v: number; txt?: string }[]; color: string }) {
    const max = Math.max(...items.map((i) => i.v), 1);
    return (
        <ul className="space-y-2">
            {items.map((i) => (
                <li key={i.label} className="grid grid-cols-[minmax(0,11rem)_1fr_auto] items-center gap-2 text-[11px]">
                    <span className="truncate text-right" title={i.label}>
                        <b>{i.label}</b>
                        {i.sub && <span className="block text-[9px] text-slate-400">{i.sub}</span>}
                    </span>
                    <span className="h-3 rounded-full bg-slate-100">
                        <span className="block h-3 rounded-full" style={{ width: `${Math.max(2, (i.v / max) * 100)}%`, background: color }} />
                    </span>
                    <span className="font-bold tabular-nums">{i.txt ?? int(i.v)}</span>
                </li>
            ))}
            {items.length === 0 && <li className="text-xs text-slate-400">Sin datos.</li>}
        </ul>
    );
}

export default function Procesamiento({ archivos, actualizado }: Props) {
    const [fMes, setMes] = useState('TODOS');
    const [fCadena, setCadena] = useState('TODAS');
    const [fEstado, setEstado] = useState('ACTIVOS');
    const [fInc, setInc] = useState('TODAS');
    const [buscar, setBuscar] = useState('');

    const meses = useMemo(() => Array.from(new Set(archivos.map(mes))).sort().reverse(), [archivos]);
    const lista = useMemo(
        () =>
            archivos.filter((a) => {
                const g = grupoEstado(a.status);
                if (fEstado === 'ACTIVOS' ? !['OK', 'ERROR'].includes(g) : fEstado !== 'TODOS' && g !== fEstado) return false;
                if (fMes !== 'TODOS' && mes(a) !== fMes) return false;
                if (fCadena !== 'TODAS' && cadena(a.nombre_archivo) !== fCadena) return false;
                if (fInc === 'CON_PROBLEMAS' && problemas(a) + toNum(a.filas_producto_sin_match) === 0) return false;
                const inc = INCIDENCIAS.find(([k]) => k === fInc);
                if (inc && inc[2](a) === 0) return false;
                const t = buscar.trim().toLowerCase();
                return !t || `${a.nombre_archivo} ${a.motivo_fallo ?? ''} ${a.detalle ?? ''}`.toLowerCase().includes(t);
            }),
        [archivos, fMes, fCadena, fEstado, fInc, buscar],
    );

    const ok = lista.filter((a) => grupoEstado(a.status) === 'OK');
    const err = lista.filter((a) => grupoEstado(a.status) === 'ERROR');
    const filas = lista.reduce((s, a) => s + toNum(a.filas_fact), 0);
    const venta = lista.reduce((s, a) => s + toNum(a.venta_total), 0);
    const calidadOk = ok.length ? ok.reduce((s, a) => s + calidad(a), 0) / ok.length : 0;
    const calidadGeneral = lista.length ? lista.reduce((s, a) => s + calidad(a), 0) / lista.length : 0;
    const sum = (f: (a: Archivo) => number) => lista.reduce((s, a) => s + f(a), 0);
    const estados = ['OK', 'ERROR', 'MANUAL', 'OTROS'].map((e) => ({ name: e, value: lista.filter((a) => grupoEstado(a.status) === e).length }));

    const sel = (label: string, value: string, set: (v: string) => void, opciones: [string, string][]) => (
        <label className="flex min-w-40 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">{label}</span>
            <select value={value} onChange={(e) => set(e.target.value)} className="bg-transparent text-xs font-semibold text-brand outline-none">
                {opciones.map(([v, l]) => (
                    <option key={v} value={v}>
                        {l}
                    </option>
                ))}
            </select>
        </label>
    );

    return (
        <AppLayout>
            <Head title="Control de Procesamiento" />
            <header className="mb-4">
                <h1 className="text-2xl font-extrabold">Control de Procesamiento y Calidad de Datos</h1>
                <p className="text-sm text-slate-500">
                    Revisión de los reportes de cadenas que se cargaron: si se leyeron bien y qué productos o sucursales falta reconocer.
                    {actualizado && <span className="ml-2 rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700">Última actualización: {new Date(actualizado).toLocaleString('es-DO')}</span>}
                </p>
            </header>

            <div className="mb-4 flex flex-wrap gap-2">
                {sel('Mes', fMes, setMes, [['TODOS', 'Todos los meses'], ...meses.map((m) => [m, m === 'SIN MES' ? 'Sin mes' : `${MESES[Number(m.slice(5, 7)) - 1]} ${m.slice(0, 4)}`] as [string, string])])}
                {sel('Cadena', fCadena, setCadena, [['TODAS', 'Todas las cadenas'], ...['CAROL', 'FARMACOS DEL NORTE', 'FARMAEXTRA', 'FARMAVALUE', 'GBC', 'LOS HIDALGOS', 'OTRA CADENA', 'UNION'].map((c) => [c, c] as [string, string])])}
                {sel('Estado', fEstado, setEstado, [['ACTIVOS', 'Activos'], ['TODOS', 'Todos'], ['OK', 'OK'], ['ERROR', 'Error'], ['MANUAL', 'Manual'], ['OTROS', 'Otros']])}
                {sel('Incidencia', fInc, setInc, [['TODAS', 'Todas'], ['CON_PROBLEMAS', 'Con problemas'], ...INCIDENCIAS.map(([k, l]) => [k, l] as [string, string])])}
                <div className="relative flex min-w-64 flex-1 items-center">
                    <Search className="absolute left-3 size-4 text-slate-400" />
                    <input value={buscar} onChange={(e) => setBuscar(e.target.value)} placeholder="Buscar archivo o motivo…" 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>

            <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4 2xl:grid-cols-7">
                <KpiCard title="Archivos" icon={<FileText className="size-4" />} accent="#6366f1">
                    <p className="text-xl font-extrabold">{int(lista.length)}</p>
                    <p className="text-[11px] text-slate-400">Total auditado</p>
                </KpiCard>
                <KpiCard title="OK" icon={<CheckCircle2 className="size-4" />} accent="#10b981">
                    <p className="text-xl font-extrabold">{int(ok.length)}</p>
                    <p className="text-[11px] text-slate-400">Archivos válidos</p>
                </KpiCard>
                <KpiCard title="Con error" icon={<XCircle className="size-4" />} accent="#ef4444">
                    <p className="text-xl font-extrabold">{int(err.length)}</p>
                    <p className="text-[11px] text-slate-400">Requiere revisión</p>
                </KpiCard>
                <KpiCard title="Calidad OK" icon={<ShieldCheck className="size-4" />} accent="#2a78d6">
                    <p className="text-xl font-extrabold">{calidadOk.toFixed(1)}%</p>
                    <p className="text-[11px] text-slate-400">General: {calidadGeneral.toFixed(1)}%</p>
                </KpiCard>
                <KpiCard title="Filas" icon={<BarChart3 className="size-4" />} accent="#8b5cf6">
                    <p className="text-xl font-extrabold">{int(filas)}</p>
                    <p className="text-[11px] text-slate-400">{moneyB(venta)}</p>
                </KpiCard>
                <KpiCard title="Sucursales no reconocidas" icon={<AlertTriangle className="size-4" />} accent="#f97316">
                    <p className="text-xl font-extrabold">{int(sum((a) => toNum(a.filas_sucursal_sin_match)))}</p>
                    <p className="text-[11px] text-slate-400">No están en el catálogo</p>
                </KpiCard>
                <KpiCard title="Dinero inválido" icon={<TrendingDown className="size-4" />} accent="#e11d48">
                    <p className="text-xl font-extrabold">{int(sum((a) => toNum(a.filas_dinero_invalido)))}</p>
                    <p className="text-[11px] text-slate-400">Precio / venta cero</p>
                </KpiCard>
            </div>

            <div className="mb-4 grid grid-cols-1 gap-4 xl:grid-cols-3">
                <Panel title="Estado de archivos" icon={<FileText className="size-4" />} accent="#6366f1">
                    <div className="h-52">
                        <ResponsiveContainer width="100%" height="100%">
                            <PieChart>
                                <Pie data={estados.filter((e) => e.value > 0)} dataKey="value" nameKey="name" innerRadius="60%" outerRadius="85%" stroke="#fff" strokeWidth={2}>
                                    {estados.filter((e) => e.value > 0).map((e) => (
                                        <Cell key={e.name} fill={COLOR_ESTADO[e.name]} />
                                    ))}
                                </Pie>
                                <Tooltip contentStyle={tooltipStyle} />
                            </PieChart>
                        </ResponsiveContainer>
                    </div>
                    <p className="flex flex-wrap justify-center gap-3 text-[10px] font-bold">
                        {estados.map((e) => (
                            <span key={e.name} className="flex items-center gap-1">
                                <span className="size-2 rounded-full" style={{ background: COLOR_ESTADO[e.name] }} /> {e.name}: {e.value}
                            </span>
                        ))}
                    </p>
                </Panel>
                <Panel title="Problemas de calidad" icon={<AlertTriangle className="size-4" />} accent="#e11d48" right="Filas afectadas">
                    <Barras color="#f97316" items={INCIDENCIAS.filter(([k]) => k !== 'PRODUCTO').map(([, l, f]) => ({ label: l, v: sum(f) })).sort((a, b) => b.v - a.v)} />
                </Panel>
                <Panel title="Peor calidad" icon={<TrendingDown className="size-4" />} accent="#f97316" right="Top 10">
                    <Barras
                        color="#f97316"
                        items={[...lista]
                            .sort((a, b) => calidad(a) - calidad(b))
                            .slice(0, 10)
                            .map((a) => ({ label: a.nombre_archivo, sub: `Riesgo ${int(problemas(a))}`, v: Math.max(1, 100 - calidad(a)), txt: `${calidad(a).toFixed(0)} pts` }))}
                    />
                </Panel>
            </div>

            <div className="grid grid-cols-1 gap-4 xl:grid-cols-[1fr_2fr]">
                <div className="space-y-4">
                    <Panel title="Sucursales no reconocidas con más venta" icon={<AlertTriangle className="size-4" />} accent="#f97316" right="Por archivo">
                        <Barras
                            color="#f97316"
                            items={[...lista]
                                .filter((a) => toNum(a.filas_sucursal_sin_match) > 0)
                                .sort((a, b) => toNum(b.filas_sucursal_sin_match) - toNum(a.filas_sucursal_sin_match))
                                .slice(0, 5)
                                .map((a) => ({ label: a.nombre_archivo, sub: `${((toNum(a.filas_sucursal_sin_match) / Math.max(1, toNum(a.filas_fact))) * 100).toFixed(1)}%`, v: toNum(a.filas_sucursal_sin_match) }))}
                        />
                    </Panel>
                    <Panel title="Archivos con productos pendientes de catálogo" icon={<FileText className="size-4" />} accent="#6366f1" right="Pendiente catálogo">
                        <Barras
                            color="#6366f1"
                            items={[...lista]
                                .filter((a) => toNum(a.filas_producto_sin_match) > 0)
                                .sort((a, b) => toNum(b.filas_producto_sin_match) - toNum(a.filas_producto_sin_match))
                                .slice(0, 8)
                                .map((a) => ({ label: a.nombre_archivo, sub: `Sin catálogo: ${int(a.filas_producto_sin_match)}`, v: toNum(a.filas_producto_sin_match) }))}
                        />
                    </Panel>
                </div>
                <Panel title="Detalle de archivos procesados" icon={<FileText className="size-4" />} accent="#2a78d6" right={`${lista.length} archivos visibles`}>
                    <div className="max-h-[36rem] overflow-auto">
                        <table className="w-full min-w-[900px] text-[11px] tabular-nums">
                            <thead className="sticky top-0 bg-white text-[10px] tracking-wider text-slate-400 uppercase">
                                <tr>
                                    {['Archivo', 'Estado', 'Calidad', 'Filas', 'Venta', 'Suc. no rec.', 'Sin provincia', 'Dinero', 'Motivo / última ejecución'].map((h, i) => (
                                        <th key={h} className={clsx('py-2', i >= 2 && i <= 7 ? 'text-right' : 'text-left', 'px-1')}>
                                            {h}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {lista.map((a) => {
                                    const g = grupoEstado(a.status);
                                    const q = calidad(a);
                                    return (
                                        <tr key={a.nombre_archivo} className="border-t border-slate-100 align-top">
                                            <td className="max-w-56 px-1 py-2">
                                                <span className="block truncate font-bold" title={a.nombre_archivo}>
                                                    {a.nombre_archivo}
                                                </span>
                                                <span className="text-[9px] text-slate-400">
                                                    Intentos: {a.ejecuciones ?? 0} · {a.fecha_min ?? 's/f'} → {a.fecha_max ?? 's/f'}
                                                </span>
                                            </td>
                                            <td className="px-1">
                                                <span className="rounded px-1.5 py-0.5 text-[9px] font-bold text-white" style={{ background: COLOR_ESTADO[g] }}>
                                                    {norm(a.status)}
                                                </span>
                                            </td>
                                            <td className="px-1 text-right">
                                                <span className={clsx('rounded-full px-1.5 font-bold', q >= 95 ? 'bg-emerald-50 text-emerald-700' : q >= 70 ? 'bg-amber-50 text-amber-700' : 'bg-red-50 text-red-600')}>{q.toFixed(0)}</span>
                                            </td>
                                            <td className="px-1 text-right">{int(a.filas_fact)}</td>
                                            <td className="px-1 text-right">{moneyB(a.venta_total)}</td>
                                            <td className="px-1 text-right">{int(a.filas_sucursal_sin_match)}</td>
                                            <td className="px-1 text-right">{int(a.filas_provincia_null)}</td>
                                            <td className="px-1 text-right">{int(a.filas_dinero_invalido)}</td>
                                            <td className="px-1">
                                                <p className="line-clamp-3 text-[10px] font-semibold text-slate-600" title={a.motivo_fallo || a.detalle || ''}>
                                                    {a.motivo_fallo || a.detalle}
                                                </p>
                                                <p className="text-[9px] text-slate-400">{a.ultima_ejecucion ? String(a.ultima_ejecucion).slice(0, 16).replace('T', ' ') : 'Sin fecha'}</p>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                </Panel>
            </div>
        </AppLayout>
    );
}
