import { router } from '@inertiajs/react';
import { FileUp, X } from 'lucide-react';
import { useState } from 'react';
import { money } from '@/lib/format';

type Fila = { nombre: string; zona: string; cobro_real: number; meta_cobro: number };
type Resultado = { ok?: boolean; message?: string; noEncontrados?: unknown[]; ambiguos?: unknown[]; duplicados?: unknown[]; invalidos?: unknown[]; [k: string]: unknown };

// Mismos encabezados que aceptaba la app anterior.
const H_VENDEDOR = ['VENDEDOR', 'NOMBRE', 'NOMBRE VENDEDOR'];
const H_ZONA = ['ZONA'];
const H_META = ['META', 'META COBRO', 'META COBROS', 'META DE COBRO', 'META DE COBROS', 'PRESUPUESTO COBRO'];
const H_COBRADO = ['COBRADO', 'COBRO REAL', 'COBROS REAL', 'COBROS REALES', 'REAL', 'MONTO COBRADO'];
const MESES = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO', 'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE'];

const norm = (v: unknown) =>
    String(v ?? '')
        .normalize('NFD')
        .replace(/[̀-ͯ]/g, '')
        .trim()
        .toUpperCase()
        .replace(/\s+/g, ' ');
const num = (v: unknown): number | null => {
    if (v === null || v === undefined || v === '') return null;
    if (typeof v === 'number') return Number.isFinite(v) ? v : null;
    const n = parseFloat(String(v).replace(/[^0-9.-]/g, ''));
    return Number.isFinite(n) ? n : null;
};

function leerFilas(matriz: unknown[][]): { rows: Fila[]; errors: string[] } {
    const rows: Fila[] = [];
    const errors: string[] = [];
    const idx = (fila: string[], opciones: string[]) => fila.findIndex((c) => opciones.includes(c));
    let inicio = -1;
    let col = { v: -1, z: -1, m: -1, c: -1 };
    for (let i = 0; i < Math.min(matriz.length, 30); i++) {
        const fila = (matriz[i] ?? []).map(norm);
        const v = idx(fila, H_VENDEDOR);
        const z = idx(fila, H_ZONA);
        if (v >= 0 && z >= 0) {
            inicio = i;
            col = { v, z, m: idx(fila, H_META), c: idx(fila, H_COBRADO) };
            break;
        }
    }
    if (inicio < 0) return { rows, errors: ['No se encontró la fila de encabezados: VENDEDOR | ZONA | META | COBRADO.'] };
    if (col.m < 0 || col.c < 0) return { rows, errors: [`Falta el encabezado ${[col.m < 0 ? 'META' : '', col.c < 0 ? 'COBRADO' : ''].filter(Boolean).join(' y ')} (fila ${inicio + 1}).`] };
    for (let i = inicio + 1; i < matriz.length; i++) {
        const f = matriz[i] ?? [];
        const nombre = norm(f[col.v]);
        if (!nombre || nombre === 'TOTAL' || nombre.startsWith('TOTAL ')) continue;
        const meta = num(f[col.m]);
        const cobrado = num(f[col.c]);
        if (meta === null || cobrado === null) {
            errors.push(`Fila ${i + 1} (${nombre}): falta META o COBRADO.`);
            continue;
        }
        rows.push({ nombre, zona: norm(f[col.z]), cobro_real: cobrado, meta_cobro: meta });
    }
    if (!rows.length && !errors.length) errors.push('El archivo no contiene vendedores.');
    return { rows, errors };
}

/** Mes a partir del nombre de la hoja o del archivo ("COBROS NOVIEMBRE 2026.xlsx" → 2026-11-01). */
function mesDe(...textos: string[]): string | null {
    for (const t of textos) {
        const n = norm(t);
        const anio = n.match(/20\d{2}/)?.[0];
        const m = MESES.findIndex((x) => n.includes(x));
        if (anio && m >= 0) return `${anio}-${String(m + 1).padStart(2, '0')}-01`;
    }
    return null;
}

function csrf() {
    const m = document.cookie.match(/XSRF-TOKEN=([^;]+)/);
    return m ? decodeURIComponent(m[1]!) : '';
}

export function CargarCobros({ mesPorDefecto, onClose }: { mesPorDefecto: string; onClose: () => void }) {
    const [mes, setMes] = useState(mesPorDefecto);
    const [archivo, setArchivo] = useState('');
    const [filas, setFilas] = useState<Fila[]>([]);
    const [errores, setErrores] = useState<string[]>([]);
    const [res, setRes] = useState<Resultado | null>(null);
    const [ocupado, setOcupado] = useState(false);
    const [mensaje, setMensaje] = useState('');

    const enviar = async (aplicar: boolean, rows = filas, m = mes, nombre = archivo) => {
        setOcupado(true);
        setMensaje('');
        try {
            const r = await fetch('/comisiones-vendedores/cobros', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-XSRF-TOKEN': csrf() },
                body: JSON.stringify({ mes: m, archivo: nombre, aplicar, rows }),
            });
            const j = (await r.json()) as Resultado;
            if (!r.ok) throw new Error(j.message ?? 'Error al procesar el archivo.');
            setRes(j);
            if (aplicar && j.ok !== false) {
                setMensaje('Cobros aplicados.');
                router.reload();
            }
        } catch (e) {
            setMensaje(e instanceof Error ? e.message : 'Error al procesar el archivo.');
        } finally {
            setOcupado(false);
        }
    };

    const leer = async (file: File) => {
        setRes(null);
        setMensaje('');
        setArchivo(file.name);
        const XLSX = await import('xlsx');
        const wb = XLSX.read(await file.arrayBuffer(), { type: 'array' });
        const hoja = wb.Sheets[wb.SheetNames[0]!];
        const matriz = hoja ? (XLSX.utils.sheet_to_json(hoja, { header: 1, defval: null, raw: true, blankrows: true }) as unknown[][]) : [];
        const { rows, errors } = leerFilas(matriz);
        const m = mesDe(wb.SheetNames[0] ?? '', file.name) ?? mes;
        setFilas(rows);
        setErrores(errors);
        setMes(m);
        if (rows.length) await enviar(false, rows, m, file.name);
    };

    const problemas = (['noEncontrados', 'ambiguos', 'duplicados', 'invalidos'] as const).filter((k) => Array.isArray(res?.[k]) && (res![k] as unknown[]).length > 0);
    const bloqueado = errores.length > 0 || !res || res.ok === false || problemas.length > 0;

    return (
        <div className="fixed inset-0 z-50 grid place-items-center bg-slate-900/40 p-4">
            <div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl bg-white p-5 shadow-2xl">
                <div className="mb-3 flex items-center justify-between">
                    <h2 className="text-lg font-extrabold">Cargar cobros del mes</h2>
                    <button type="button" onClick={onClose} className="text-slate-400 hover:text-slate-700" aria-label="Cerrar">
                        <X className="size-5" />
                    </button>
                </div>
                <p className="mb-3 text-xs text-slate-500">Excel con encabezados VENDEDOR | ZONA | META | COBRADO. Primero se valida sin guardar; luego puedes aplicarlo.</p>

                <div className="mb-3 flex flex-wrap items-center gap-2">
                    <label className="text-xs font-semibold">
                        Mes{' '}
                        <input type="month" value={mes.slice(0, 7)} onChange={(e) => setMes(`${e.target.value}-01`)} className="ml-1 rounded-lg border border-slate-200 px-2 py-1" />
                    </label>
                    <label className="flex cursor-pointer items-center gap-2 rounded-lg border border-dashed border-brand px-3 py-2 text-xs font-semibold text-brand hover:bg-indigo-50">
                        <FileUp className="size-4" /> {archivo || 'Elegir archivo .xlsx'}
                        <input type="file" accept=".xlsx,.xls,.csv" className="hidden" onChange={(e) => e.target.files?.[0] && void leer(e.target.files[0])} />
                    </label>
                </div>

                {errores.length > 0 && (
                    <ul className="mb-3 list-disc rounded-lg bg-red-50 p-3 pl-7 text-xs text-red-700">
                        {errores.map((e) => (
                            <li key={e}>{e}</li>
                        ))}
                    </ul>
                )}

                {filas.length > 0 && (
                    <div className="mb-3 max-h-56 overflow-y-auto rounded-lg border border-slate-100">
                        <table className="w-full text-[11px] tabular-nums">
                            <thead className="sticky top-0 bg-slate-50 text-[10px] text-slate-500 uppercase">
                                <tr>
                                    <th className="px-2 py-1 text-left">Vendedor</th>
                                    <th className="text-left">Zona</th>
                                    <th className="text-right">Meta</th>
                                    <th className="px-2 text-right">Cobrado</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filas.map((f, i) => (
                                    <tr key={`${f.nombre}-${i}`} className="border-t border-slate-100">
                                        <td className="px-2 py-1">{f.nombre}</td>
                                        <td>{f.zona}</td>
                                        <td className="text-right">{money(f.meta_cobro)}</td>
                                        <td className="px-2 text-right">{money(f.cobro_real)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}

                {res && (
                    <div className={`mb-3 rounded-lg p-3 text-xs ${bloqueado ? 'bg-amber-50 text-amber-800' : 'bg-emerald-50 text-emerald-800'}`}>
                        {res.message && <p className="font-semibold">{res.message}</p>}
                        {problemas.map((k) => (
                            <p key={k}>
                                <b>{k}:</b> {JSON.stringify(res[k])}
                            </p>
                        ))}
                        {!bloqueado && <p>Validación correcta: puedes aplicar los cobros.</p>}
                    </div>
                )}
                {mensaje && <p className="mb-3 text-xs font-semibold text-brand">{mensaje}</p>}

                <div className="flex justify-end gap-2">
                    <button type="button" onClick={onClose} className="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold">
                        Cerrar
                    </button>
                    <button type="button" disabled={bloqueado || ocupado} onClick={() => void enviar(true)} className="rounded-lg bg-brand px-4 py-2 text-xs font-bold text-white disabled:opacity-40">
                        {ocupado ? 'Procesando…' : 'Aplicar cobros'}
                    </button>
                </div>
            </div>
        </div>
    );
}
