import { Copy, Download, FileUp, Pencil, RotateCcw, Search, Send, Sparkles } from 'lucide-react';
import clsx from 'clsx';
import { useRef, useState } from 'react';
import { Paginacion } from '@/components/Paginacion';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { descargarExcel } from '@/lib/http';
import { int, money } from '@/lib/format';
import { leer, MESES, useAccion, useLectura } from './api';
import { Btn, Caja, elegir, Estado, input, Msg, pedirTexto, Tabla } from './ui';
import type { Version } from './tipos';

type Fila = { id: number; mes: number; tipo: string; producto: string; idProducto: string; unidadesFinal: number; precioFinal: number; ventasFinal: number; unidadesSugeridas: number; ventasSugeridas: number; estadoProducto: string; observacion?: string | null };
type Detalle = { rows: Fila[]; page: number; totalPages: number; totalRows: number; types?: string[] };

const leerCol = (r: Record<string, unknown>, nombres: string[]) => {
    for (const n of nombres) if (n in r && r[n] !== '' && r[n] !== null) return r[n];
    return undefined;
};
const num = (v: unknown) => {
    const n = typeof v === 'number' ? v : parseFloat(String(v ?? '').replace(/[^0-9.-]/g, ''));
    return Number.isFinite(n) ? n : 0;
};

/** Lee el Excel de presupuesto con las mismas reglas que la app anterior. */
async function leerPresupuesto(file: File, anio: number) {
    const XLSX = await import('xlsx');
    const wb = XLSX.read(await file.arrayBuffer(), { type: 'array', cellDates: true });
    const datos = XLSX.utils.sheet_to_json<Record<string, unknown>>(wb.Sheets[wb.SheetNames[0]!]!, { defval: '' }).map((r) =>
        Object.fromEntries(Object.entries(r).map(([k, v]) => [k.trim().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/\s+/g, '_'), v])),
    );
    const filas = datos
        .map((r, i) => {
            const f = leerCol(r, ['fecha', 'mes', 'periodo']);
            let fecha: string | null = null;
            if (f instanceof Date) fecha = `${f.getFullYear()}-${String(f.getMonth() + 1).padStart(2, '0')}-01`;
            else if (f !== undefined) {
                const s = String(f).trim();
                const m = s.match(/^(\d{4})-(\d{1,2})/) ?? s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);
                if (m) fecha = m.length === 3 ? `${m[1]}-${m[2]!.padStart(2, '0')}-01` : `${m[3]}-${m[2]!.padStart(2, '0')}-01`;
            }
            const producto = String(leerCol(r, ['producto', 'descripcion', 'producto_nombre', 'nombre_producto']) ?? '').trim();
            const id = String(leerCol(r, ['id_producto', 'producto_id', 'codigo_producto', 'item_code']) ?? '').trim();
            const unidades = Math.max(num(leerCol(r, ['unidades', 'cantidad'])), 0);
            const ventas = Math.max(num(leerCol(r, ['ventas', 'presupuesto', 'presupuesto_ventas'])), 0);
            if (!fecha && !producto && !id && !unidades && !ventas) return null;
            if (!fecha) throw new Error(`Fila ${i + 2}: fecha o mes inválido.`);
            if (Number(fecha.slice(0, 4)) !== anio) throw new Error(`Fila ${i + 2}: la fecha ${fecha} no pertenece a ${anio}.`);
            if (!producto && !id) throw new Error(`Fila ${i + 2}: falta producto o id_producto.`);
            return {
                fecha,
                id_producto: id || null,
                producto: producto || id,
                tipo: String(leerCol(r, ['tipo', 'tipo_producto', 'grupo', 'clasificacion']) ?? '').trim() || null,
                unidades,
                precio_promedio: Math.max(num(leerCol(r, ['precio_promedio', 'precio', 'precio_unitario'])), 0),
                ventas,
            };
        })
        .filter((x): x is NonNullable<typeof x> => x !== null);
    if (!filas.length) throw new Error('El archivo no contiene filas utilizables.');
    const vistos = new Set<string>();
    for (const f of filas) {
        const k = `${f.fecha}|${f.id_producto ?? `ND:${f.producto}`}`;
        if (vistos.has(k)) throw new Error(`El archivo contiene combinaciones duplicadas de mes + producto (${k}).`);
        vistos.add(k);
    }
    return filas;
}

export function TabPresupuesto({ anio, versiones, recargarTodo }: { anio: number; versiones: Version[]; recargarTodo: () => void }) {
    const pub = versiones.find((v) => v.estado === 'PUBLICADO') ?? versiones[0];
    const [vid, setVid] = useState<number | undefined>(pub?.id);
    const [buscar, setBuscar] = useState('');
    const [mes, setMes] = useState<number | ''>('');
    const [tipo, setTipo] = useState('');
    const [pagina, setPagina] = useState(1);
    const [filtro, setFiltro] = useState({ buscar: '', mes: '' as number | '', tipo: '' });
    const det = useLectura<Detalle>('get_presupuesto_admin_detalle', vid ? { p_version_id: vid, p_search: filtro.buscar || null, p_mes: filtro.mes || null, p_tipo: filtro.tipo || null, p_page: pagina, p_page_size: 50 } : null);
    const { msg, setMsg, ocupado, ejecutar } = useAccion(() => {
        void det.recargar();
        recargarTodo();
    });
    const [prop, setProp] = useState({ crecimiento: 5, precio: 0, nombre: '' });
    const [ajuste, setAjuste] = useState({ porcentaje: 0, campo: 'VENTAS', mes: '' as number | '', tipo: '' });
    const [editar, setEditar] = useState<Fila | null>(null);
    const [edit, setEdit] = useState({ unidades: '', precio: '', ventas: '', observacion: '' });
    const v = versiones.find((x) => x.id === vid);
    const archivo = useRef<HTMLInputElement>(null);

    const exportar = async () => {
        if (!vid) return;
        try {
            const r = await leer<{ rows?: Record<string, unknown>[] }>('get_presupuesto_admin_export', { p_version_id: vid });
            await descargarExcel(`presupuesto_${vid}_${anio}.xlsx`, { presupuesto: r.rows ?? (Array.isArray(r) ? (r as Record<string, unknown>[]) : []) });
        } catch (e) {
            setMsg({ t: 'err', m: e instanceof Error ? e.message : String(e) });
        }
    };

    const importar = async (file: File) => {
        try {
            const filas = await leerPresupuesto(file, anio);
            const modo = await elegir(`¿Importar ${file.name}?`, `Se leyeron ${int(filas.length)} filas del año ${anio}. Puedes guardarla como borrador para revisarla o publicarla de una vez (reemplaza a la versión publicada).`, [
                { valor: 'borrador', label: 'Importar como borrador', variante: 'outline' },
                { valor: 'publicar', label: 'Importar y publicar' },
            ]);
            if (!modo) return;
            const publicar = modo === 'publicar';
            await ejecutar('importar_presupuesto_fiel_v1', { p_anio: anio, p_nombre: `Importación ${file.name} - ${anio}`, p_archivo: file.name, p_filas: filas, p_publicar: publicar }, (r) => `Importación terminada: ${JSON.stringify(r).slice(0, 200)}`);
        } catch (e) {
            setMsg({ t: 'err', m: e instanceof Error ? e.message : String(e) });
        }
    };

    return (
        <>
            <Msg msg={msg} />
            <Caja
                titulo="Versiones de presupuesto"
                sub={`Año ${anio}. Solo una versión puede estar publicada.`}
                derecha={
                    <>
                        <Btn disabled={ocupado} onClick={() => archivo.current?.click()}>
                            <FileUp className="size-4" /> Importar Excel
                        </Btn>
                        <input
                            ref={archivo}
                            type="file"
                            accept=".xlsx,.xls,.csv"
                            className="hidden"
                            onChange={(e) => {
                                const f = e.target.files?.[0];
                                e.target.value = '';
                                if (f) void importar(f);
                            }}
                        />
                    </>
                }
                className="mb-4"
            >
                <Tabla cols={['ID', 'Nombre', 'Estado', 'Origen', ['Filas', 'r'], ['Productos', 'r'], ['Ventas', 'r'], ['Acciones', 'r']]}>
                    {versiones.map((x) => (
                        <tr key={x.id} className={clsx('border-t border-border', x.id === vid && 'bg-slate-50 shadow-[inset_3px_0_0_var(--color-ibero-orange)]')}>
                            <td className="px-2 py-1.5 font-medium text-muted-foreground">#{x.id}</td>
                            <td className="px-2">
                                <button type="button" onClick={() => (setVid(x.id), setPagina(1))} className="text-left font-semibold hover:underline">
                                    {x.nombre}
                                </button>
                            </td>
                            <td className="px-2">
                                <span className={clsx('rounded-full px-2 py-0.5 text-xs font-medium', x.estado === 'PUBLICADO' ? 'bg-emerald-50 text-emerald-700' : x.estado === 'BORRADOR' ? 'bg-amber-50 text-amber-700' : 'bg-slate-100 text-muted-foreground')}>{x.estado}</span>
                            </td>
                            <td className="px-2 text-xs text-muted-foreground">{x.origen}</td>
                            <td className="px-2 text-right">{int(x.filas)}</td>
                            <td className="px-2 text-right">{int(x.productos)}</td>
                            <td className="px-2 text-right">{money(x.ventas)}</td>
                            <td className="px-2 text-right whitespace-nowrap">
                                <button type="button" title="Clonar" disabled={ocupado} onClick={() => void ejecutar('clonar_presupuesto_version', { p_version_id: x.id, p_nombre: `Copia de ${x.nombre}` }, 'Versión clonada como borrador.')} className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground">
                                    <Copy className="size-4" />
                                </button>
                                <button
                                    type="button"
                                    title="Renombrar"
                                    disabled={ocupado}
                                    onClick={async () => {
                                        const n = await pedirTexto(`Renombrar la versión #${x.id}`, x.nombre, { etiqueta: 'Nombre' });
                                        if (n && n.trim() !== x.nombre) void ejecutar('renombrar_presupuesto_version_v3_5_2', { p_version_id: x.id, p_nombre: n.trim() }, 'Versión renombrada.');
                                    }}
                                    className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                                >
                                    <Pencil className="size-4" />
                                </button>
                                {x.estado !== 'PUBLICADO' && (
                                    <button
                                        type="button"
                                        title="Validar y publicar"
                                        disabled={ocupado}
                                        onClick={async () => {
                                            try {
                                                const val = await leer<Record<string, unknown>>('validar_version_presupuesto_parcial', { p_version_id: x.id });
                                                if (val.ok === false) return setMsg({ t: 'err', m: `No se puede publicar: ${String(val.message ?? JSON.stringify(val).slice(0, 300))}` });
                                                await ejecutar('publicar_presupuesto_version_parcial', { p_version_id: x.id }, 'Versión publicada.', `¿Publicar #${x.id}? Reemplaza a la versión publicada actual.`);
                                            } catch (e) {
                                                setMsg({ t: 'err', m: e instanceof Error ? e.message : String(e) });
                                            }
                                        }}
                                        className="rounded-md p-1.5 text-emerald-600 hover:bg-emerald-50"
                                    >
                                        <Send className="size-4" />
                                    </button>
                                )}
                            </td>
                        </tr>
                    ))}
                </Tabla>
            </Caja>

            <div className="mb-4 grid grid-cols-1 gap-4 xl:grid-cols-2">
                <Caja titulo="Generar propuesta automática" sub="Crea un borrador a partir del histórico con crecimiento y aumento de precio.">
                    <div className="flex flex-wrap items-end gap-3 text-sm font-medium">
                        <label>
                            Crecimiento %<input type="number" step="0.1" value={prop.crecimiento} onChange={(e) => setProp({ ...prop, crecimiento: Number(e.target.value) })} className={`${input} mt-1.5 block w-24`} />
                        </label>
                        <label>
                            Aumento precio %<input type="number" step="0.1" value={prop.precio} onChange={(e) => setProp({ ...prop, precio: Number(e.target.value) })} className={`${input} mt-1.5 block w-24`} />
                        </label>
                        <label className="flex-1">
                            Nombre<input value={prop.nombre} onChange={(e) => setProp({ ...prop, nombre: e.target.value })} placeholder={`Propuesta ${anio}`} className={`${input} mt-1.5 block w-full`} />
                        </label>
                        <Btn disabled={ocupado} onClick={() => void ejecutar('generar_presupuesto_propuesta', { p_anio: anio, p_crecimiento_general_pct: prop.crecimiento, p_incremento_precio_pct: prop.precio, p_nombre: prop.nombre || null }, 'Propuesta generada como borrador.', '¿Generar una nueva propuesta? Puede tardar.')}>
                            <Sparkles className="size-4" /> Generar
                        </Btn>
                    </div>
                </Caja>
                <Caja titulo={`Ajuste masivo a la versión #${vid ?? ''}`} sub="Aplica un porcentaje a ventas, unidades o precio (opcional por mes o tipo).">
                    <div className="flex flex-wrap items-end gap-3 text-sm font-medium">
                        <label>
                            %<input type="number" step="0.1" value={ajuste.porcentaje} onChange={(e) => setAjuste({ ...ajuste, porcentaje: Number(e.target.value) })} className={`${input} mt-1.5 block w-20`} />
                        </label>
                        <label>
                            Campo
                            <select value={ajuste.campo} onChange={(e) => setAjuste({ ...ajuste, campo: e.target.value })} className={`${input} mt-1.5 block`}>
                                {['VENTAS', 'UNIDADES', 'PRECIO'].map((c) => (
                                    <option key={c}>{c}</option>
                                ))}
                            </select>
                        </label>
                        <label>
                            Mes
                            <select value={ajuste.mes} onChange={(e) => setAjuste({ ...ajuste, mes: e.target.value ? Number(e.target.value) : '' })} className={`${input} mt-1.5 block`}>
                                <option value="">Todos</option>
                                {MESES.map((m, i) => (
                                    <option key={m} value={i + 1}>
                                        {m}
                                    </option>
                                ))}
                            </select>
                        </label>
                        <label>
                            Tipo
                            <select value={ajuste.tipo} onChange={(e) => setAjuste({ ...ajuste, tipo: e.target.value })} className={`${input} mt-1.5 block`}>
                                <option value="">Todos</option>
                                {(det.data?.types ?? ['ETICOS', 'GENERICOS', 'OTC']).map((t) => (
                                    <option key={t}>{t}</option>
                                ))}
                            </select>
                        </label>
                        <Btn disabled={ocupado || !vid || !ajuste.porcentaje || v?.estado === 'PUBLICADO'} onClick={() => void ejecutar('aplicar_ajuste_presupuesto', { p_version_id: vid, p_porcentaje: ajuste.porcentaje, p_campo: ajuste.campo, p_mes: ajuste.mes || null, p_tipo: ajuste.tipo || null }, 'Ajuste aplicado.', `¿Aplicar ${ajuste.porcentaje}% a ${ajuste.campo} de la versión #${vid}?`)}>
                            Aplicar
                        </Btn>
                    </div>
                    {v?.estado === 'PUBLICADO' && <p className="mt-2 text-sm text-amber-700">La versión publicada no se ajusta: clónala y ajusta el borrador.</p>}
                </Caja>
            </div>

            <Caja
                titulo={`Detalle de la versión #${vid ?? ''}`}
                sub={v ? `${v.nombre} · ${int(det.data?.totalRows)} filas` : ''}
                derecha={
                    <Btn tono="neutro" onClick={() => void exportar()}>
                        <Download className="size-4" /> Exportar
                    </Btn>
                }
            >
                <form
                    className="mb-4 flex flex-wrap gap-2"
                    onSubmit={(e) => {
                        e.preventDefault();
                        setPagina(1);
                        setFiltro({ buscar, mes, tipo });
                    }}
                >
                    <div className="relative">
                        <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="Producto o código" className={`${input} pl-9`} />
                    </div>
                    <select value={mes} onChange={(e) => setMes(e.target.value ? Number(e.target.value) : '')} className={input}>
                        <option value="">Todos los meses</option>
                        {MESES.map((m, i) => (
                            <option key={m} value={i + 1}>
                                {m}
                            </option>
                        ))}
                    </select>
                    <select value={tipo} onChange={(e) => setTipo(e.target.value)} className={input}>
                        <option value="">Todos los tipos</option>
                        {(det.data?.types ?? []).map((t) => (
                            <option key={t}>{t}</option>
                        ))}
                    </select>
                    <Btn type="submit" tono="neutro">
                        Buscar
                    </Btn>
                </form>
                <Estado cargando={det.cargando} error={det.error} />
                <Tabla cols={['Mes', 'Producto', 'Tipo', ['Unidades', 'r'], ['Precio', 'r'], ['Ventas', 'r'], ['Sugerido', 'r'], 'Estado', '']} min="min-w-[900px]">
                    {(det.data?.rows ?? []).map((f) => (
                        <tr key={f.id} className="border-t border-border">
                            <td className="px-2 py-1.5">{MESES[f.mes - 1]?.slice(0, 3)}</td>
                            <td className="px-2">
                                <span className="block font-semibold">{f.producto}</span>
                                <span className="text-xs text-muted-foreground">{f.idProducto}</span>
                            </td>
                            <td className="px-2">{f.tipo}</td>
                            <td className="px-2 text-right">{int(f.unidadesFinal)}</td>
                            <td className="px-2 text-right">{money(f.precioFinal)}</td>
                            <td className="px-2 text-right font-bold">{money(f.ventasFinal)}</td>
                            <td className="px-2 text-right text-muted-foreground">{money(f.ventasSugeridas)}</td>
                            <td className="px-2 text-xs">{f.estadoProducto}</td>
                            <td className="px-2 text-right whitespace-nowrap">
                                <button type="button" title="Editar" onClick={() => (setEditar(f), setEdit({ unidades: String(f.unidadesFinal), precio: String(f.precioFinal), ventas: String(f.ventasFinal), observacion: f.observacion ?? '' }))} className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground">
                                    <Pencil className="size-4" />
                                </button>
                                <button type="button" title="Restaurar valor sugerido" onClick={() => void ejecutar('restaurar_presupuesto_detalle', { p_detalle_id: f.id }, 'Línea restaurada.', '¿Restaurar el valor sugerido de esta línea?')} className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground">
                                    <RotateCcw className="size-4" />
                                </button>
                            </td>
                        </tr>
                    ))}
                </Tabla>
                <div className="-mx-5 -mb-5 mt-4">
                    <Paginacion pagina={det.data?.page ?? pagina} total={det.data?.totalRows ?? 0} porPagina={50} onChange={setPagina} />
                </div>
            </Caja>

            <Dialog open={editar !== null} onOpenChange={(o) => !o && !ocupado && setEditar(null)}>
                <DialogContent>
                    {editar && (
                        <form
                            className="grid gap-4"
                            onSubmit={async (e) => {
                                e.preventDefault();
                                const r = await ejecutar('actualizar_presupuesto_detalle', { p_detalle_id: editar.id, p_unidades_manual: edit.unidades === '' ? null : Number(edit.unidades), p_precio_manual: edit.precio === '' ? null : Number(edit.precio), p_ventas_manual: edit.ventas === '' ? null : Number(edit.ventas), p_observacion: edit.observacion || null }, 'Línea actualizada.');
                                if (r) setEditar(null);
                            }}
                        >
                            <DialogHeader>
                                <DialogTitle>{editar.producto}</DialogTitle>
                                <DialogDescription>
                                    {MESES[editar.mes - 1]} · {editar.idProducto}. Los valores que cambies quedan como manuales; con «Restaurar» vuelves al sugerido.
                                </DialogDescription>
                            </DialogHeader>
                            <div className="grid gap-3 sm:grid-cols-3">
                                {([
                                    ['unidades', 'Unidades'],
                                    ['precio', 'Precio'],
                                    ['ventas', 'Ventas'],
                                ] as const).map(([k, l]) => (
                                    <label key={k} className="block text-sm font-medium">
                                        {l}
                                        <input type="number" step="0.01" value={edit[k]} onChange={(e) => setEdit({ ...edit, [k]: e.target.value })} className={`${input} mt-1.5 block w-full text-right tabular-nums`} />
                                    </label>
                                ))}
                            </div>
                            <label className="block text-sm font-medium">
                                Observación <span className="font-normal text-muted-foreground">(opcional)</span>
                                <input value={edit.observacion} onChange={(e) => setEdit({ ...edit, observacion: e.target.value })} className={`${input} mt-1.5 block w-full`} />
                            </label>
                            <DialogFooter>
                                <Btn tono="neutro" onClick={() => setEditar(null)}>
                                    Cancelar
                                </Btn>
                                <Btn type="submit" disabled={ocupado}>
                                    {ocupado ? 'Guardando…' : 'Guardar línea'}
                                </Btn>
                            </DialogFooter>
                        </form>
                    )}
                </DialogContent>
            </Dialog>
        </>
    );
}
