import { celdaTexto } from '../tesoreria/excel-movimientos';
import { FilaStock, ResumenStock, SumaMoneda } from './stock-consulta';

/** Hojas de Excel y filas de PDF de Stock por depósito. Puro: el servicio solo lee y entrega. */

export type FilaExport = FilaStock & { categoria: string | null; marca: string | null };

const SIMBOLOS: Record<string, { simbolo: string; decimales: number }> = {
  PYG: { simbolo: 'Gs.', decimales: 0 },
  USD: { simbolo: 'US$', decimales: 2 },
  BRL: { simbolo: 'R$', decimales: 2 },
  ARS: { simbolo: '$', decimales: 2 },
};

/** Espejo de `fmtMoneda` del front (`_standards/enums/monedas.js`): PYG sin decimales, otra moneda sin entrada, su código con 2 decimales. */
export function fmtMonedaTexto(valor: number | null, codigo: string): string {
  if (valor == null) return '—';
  const m = SIMBOLOS[codigo] ?? { simbolo: codigo || 'Gs.', decimales: codigo ? 2 : 0 };
  const n = Number(valor).toLocaleString('es-PY', { minimumFractionDigits: m.decimales, maximumFractionDigits: m.decimales });
  return `${m.simbolo} ${n}`;
}

export const fmtCantidad = (n: number | null): string => (n == null ? '—' : n.toLocaleString('es-PY', { maximumFractionDigits: 4 }));

export const fmtSumas = (sumas: SumaMoneda[] | undefined): string => (sumas?.length ? sumas.map((s) => fmtMonedaTexto(s.valor, s.moneda)).join(' + ') : '—');

const fmtPrecio = (p: { valor: number | null; moneda: string } | undefined): string => (p && p.valor != null ? fmtMonedaTexto(p.valor, p.moneda) : '—');
const fmtTotal = (p: { total: number | null; moneda: string } | undefined): string => (p && p.total != null ? fmtMonedaTexto(p.total, p.moneda) : '—');

const redondear = (n: number) => Math.round(n * 10_000) / 10_000;

export function hojaStock(filas: FilaExport[], resumen: ResumenStock, verCosto: boolean): (string | number)[][] {
  const encabezado = ['Código', 'Producto', 'Categoría', 'Marca', 'Disponible', 'Reservada', ...(verCosto ? ['Costo', 'Total costo'] : []), 'Venta', 'Total venta', 'Mínimo', 'Máximo', 'Ubicación'];
  const cuerpo = filas.map((f) => [
    celdaTexto(f.producto.cod_producto),
    celdaTexto(f.producto.descripcion),
    celdaTexto(f.categoria),
    celdaTexto(f.marca),
    f.cantidad_disponible,
    f.cantidad_reservada,
    ...(verCosto ? [fmtPrecio(f.precios.costo), fmtTotal(f.precios.costo)] : []),
    fmtPrecio(f.precios.venta),
    fmtTotal(f.precios.venta),
    f.stock_minimo,
    f.stock_maximo ?? '',
    celdaTexto(f.ubicacion),
  ]);
  const total = ['', 'TOTAL', '', '', redondear(resumen.unidades), '', ...(verCosto ? ['', fmtSumas(resumen.costo)] : []), '', fmtSumas(resumen.venta), '', '', ''];
  return [encabezado, ...cuerpo, total];
}

/** Anchos de columna de la hoja, en el mismo orden que `hojaStock`. */
export const anchosHojaStock = (verCosto: boolean): { wch: number }[] =>
  [14, 38, 18, 18, 12, 12, ...(verCosto ? [16, 18] : []), 16, 18, 10, 10, 18].map((wch) => ({ wch }));

interface ColumnaPdf {
  key: string;
  label: string;
  weight: number;
  align?: 'right' | 'left';
}

/** Columnas y filas para `reporte-tabla`: todo ya formateado como texto (el generador, sin `type`, no reformatea). */
export function tablaPdfStock(filas: FilaExport[], verCosto: boolean): { columns: ColumnaPdf[]; rows: Record<string, unknown>[] } {
  const columns: ColumnaPdf[] = [
    { key: 'codigo', label: 'Código', weight: 1.3 },
    { key: 'producto', label: 'Producto', weight: 3.2 },
    { key: 'categoria', label: 'Categoría', weight: 1.6 },
    { key: 'marca', label: 'Marca', weight: 1.4 },
    { key: 'disponible', label: 'Disp.', weight: 1, align: 'right' },
    { key: 'reservada', label: 'Res.', weight: 0.9, align: 'right' },
    ...(verCosto
      ? ([
          { key: 'costo', label: 'Costo', weight: 1.5, align: 'right' },
          { key: 'total_costo', label: 'Total costo', weight: 1.7, align: 'right' },
        ] as ColumnaPdf[])
      : []),
    { key: 'venta', label: 'Venta', weight: 1.5, align: 'right' },
    { key: 'total_venta', label: 'Total venta', weight: 1.7, align: 'right' },
    { key: 'minimo', label: 'Mín.', weight: 0.9, align: 'right' },
    { key: 'maximo', label: 'Máx.', weight: 0.9, align: 'right' },
    { key: 'ubicacion', label: 'Ubic.', weight: 1.2 },
  ];
  const rows = filas.map((f) => ({
    codigo: f.producto.cod_producto ?? '',
    producto: f.producto.descripcion,
    categoria: f.categoria ?? '',
    marca: f.marca ?? '',
    disponible: fmtCantidad(f.cantidad_disponible),
    reservada: fmtCantidad(f.cantidad_reservada),
    ...(verCosto ? { costo: fmtPrecio(f.precios.costo), total_costo: fmtTotal(f.precios.costo) } : {}),
    venta: fmtPrecio(f.precios.venta),
    total_venta: fmtTotal(f.precios.venta),
    minimo: fmtCantidad(f.stock_minimo),
    maximo: f.stock_maximo != null ? fmtCantidad(f.stock_maximo) : '—',
    ubicacion: f.ubicacion ?? '',
  }));
  return { columns, rows };
}

/** Totales del PDF: con `type: 'text'` el generador no los trata como importes (sin él, un texto saldría `Gs. 0`). */
export function totalesPdfStock(resumen: ResumenStock, verCosto: boolean): { label: string; value: string; type: 'text' }[] {
  return [
    { label: 'Productos', value: fmtCantidad(resumen.filas), type: 'text' },
    { label: 'Total disponible', value: fmtCantidad(redondear(resumen.unidades)), type: 'text' },
    ...(verCosto ? [{ label: 'Valorizado al costo', value: fmtSumas(resumen.costo), type: 'text' as const }] : []),
    { label: 'Valorizado a la venta', value: fmtSumas(resumen.venta), type: 'text' },
  ];
}

/** `stock-<depósito>-<hoy>.<ext>`: espacios a guion bajo y sin caracteres que rompan un nombre de archivo. */
export function nombreArchivoStock(deposito: string, hoy: string, ext: 'xlsx' | 'pdf'): string {
  const limpio = (deposito || 'deposito').trim().replace(/\s+/g, '_').replace(/[^\p{L}\p{N}_.-]/gu, '') || 'deposito';
  return `stock-${limpio}-${hoy}.${ext}`;
}
