// ─── Gastos ─────────────────────────────────────────────────────────────────
const AREA_COLORS = {
  OFFICE:    '#3D4F5C',
  MKT:       '#C9A961',
  COMERCIAL: '#3F8A6B',
  RRHH:      '#A88A47',
  GE:        '#677A88',
};

const CAT_TO_AREA = {
  SUELDO:          'RRHH',
  ALQUILER:        'OFFICE',
  GASTO_OPERATIVO: 'GE',
  COMISION:        'COMERCIAL',
  MENSUALIDAD:     'GE',
  OTRO:            'GE',
};

const GASTO_CATS_API = [
  { value: 'SUELDO',          label: 'Sueldo' },
  { value: 'ALQUILER',        label: 'Alquiler' },
  { value: 'GASTO_OPERATIVO', label: 'Gasto operativo' },
  { value: 'COMISION',        label: 'Comisión' },
  { value: 'MENSUALIDAD',     label: 'Mensualidad' },
  { value: 'OTRO',            label: 'Otro' },
];

// Conservado por compatibilidad con código que lo importa desde window
function FormaPagoChip() { return null; }

function adaptarGasto(m) {
  return {
    id:           m.id,
    fecha:        m.fecha ? m.fecha.slice(0, 10) : '',
    area:         CAT_TO_AREA[m.categoria] ?? 'GE',
    categoria:    m.categoria,
    periodicidad: m.periodicidad,
    desc:         m.descripcion,
    monto:        Number(m.monto),
    moneda:       m.moneda,
    comp:         m.comprobanteUrl ?? null,
    usuarioId:    m.usuarioId ?? null,
    usuario:      m.usuario   ?? null,
    notas:        m.notas     ?? '',
  };
}

// Reutilizar generarPeriodos / periodoDates definidos en ingresos.jsx
// (cargado antes en el bundle). Si no existe, redefinirlos.
const _generarPeriodos = typeof generarPeriodos !== 'undefined' ? generarPeriodos : function _gen() {
  const hoy = new Date();
  const MESES = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
  const opts = [];
  for (let i = 0; i < 12; i++) {
    const d    = new Date(hoy.getFullYear(), hoy.getMonth() - i, 1);
    const mes  = d.getMonth() + 1;
    const anio = d.getFullYear();
    opts.push({
      value: `${anio}-${String(mes).padStart(2, '0')}`,
      label: `${MESES[mes - 1].charAt(0).toUpperCase() + MESES[mes - 1].slice(1)} ${anio}`,
      mes, anio,
    });
  }
  return opts;
};

const _periodoDates = typeof periodoDates !== 'undefined' ? periodoDates : function _pd(yearMonth) {
  const [anio, mes] = yearMonth.split('-').map(Number);
  const desde   = `${anio}-${String(mes).padStart(2, '0')}-01`;
  const lastDay = new Date(anio, mes, 0).getDate();
  const hasta   = `${anio}-${String(mes).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
  return { desde, hasta };
};

function Gastos() {
  const periodos       = React.useMemo(_generarPeriodos, []);
  const defaultPeriodo = periodos[0].value;

  const [area,    setArea]    = useState('Todos');
  const [periodo, setPeriodo] = useState(defaultPeriodo);
  const [openNew, setOpenNew] = useState(false);
  const [editItem, setEditItem] = useState(null);
  const [gastos,  setGastos]  = useState([]);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState(null);

  const cargar = (p) => {
    setLoading(true);
    const { desde, hasta } = _periodoDates(p);
    fetch(`${API_BASE}/api/finanzas?tipo=EGRESO&desde=${desde}&hasta=${hasta}`, { credentials: 'include' })
      .then(r => r.json())
      .then(json => {
        setGastos((Array.isArray(json) ? json : (json.data ?? [])).map(adaptarGasto));
        setLoading(false);
      })
      .catch(err => {
        console.error('[gastos fetch]', err);
        setError('Error al cargar gastos.');
        setLoading(false);
      });
  };

  useEffect(() => { cargar(defaultPeriodo); }, []);

  const handlePeriodoChange = (p) => { setPeriodo(p); cargar(p); };

  const filtered = useMemo(() => gastos.filter(g =>
    area === 'Todos' || g.area === area
  ), [gastos, area]);

  const totalARS = filtered.filter(g => g.moneda === 'ARS').reduce((s, g) => s + g.monto, 0);
  const totalUSD = filtered.filter(g => g.moneda === 'USD').reduce((s, g) => s + g.monto, 0);

  const columns = [
    { key: 'id',    label: 'ID' },
    { key: 'fecha', label: 'Fecha' },
    { key: 'area',  label: 'Área' },
    { key: 'desc',  label: 'Descripción' },
    { key: 'monto', label: 'Monto' },
    { key: 'moneda',label: 'Moneda' },
    { label: 'Comprobante', value: g => g.comp || 'sin comprobante' },
  ];

  const onCreated = (nuevo) => {
    setGastos(prev => [nuevo, ...prev]);
    setOpenNew(false);
  };

  const onUpdated = (actualizado) => {
    setGastos(prev => prev.map(g => g.id === actualizado.id ? actualizado : g));
    setEditItem(null);
  };

  if (loading) return <div className="p-8 text-slate-500">Cargando gastos…</div>;
  if (error)   return <div className="p-8 text-red-500">{error}</div>;

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Finanzas', 'Gastos']}
        title="Gastos"
        sub={`${filtered.length} registros · ${ARS(totalARS)} + ${USD(totalUSD)}`}
        actions={
          <>
            <ExportButton filename={`lanven-gastos-${new Date().toISOString().slice(0,10)}`} rows={filtered} columns={columns} count={filtered.length} />
            <Button variant="primary" size="md" icon={<I.Plus size={14} sw={2} />} onClick={() => setOpenNew(true)}>Nuevo gasto</Button>
          </>
        }
      />

      <div className="flex items-center gap-2.5 mb-4 flex-wrap">
        <Select label="Área" value={area} onChange={setArea} w="w-44"
          options={[
            { value: 'Todos',     label: 'Todas las áreas',    count: gastos.length },
            { value: 'OFFICE',    label: 'Office',              dot: AREA_COLORS.OFFICE,    count: gastos.filter(g => g.area === 'OFFICE').length },
            { value: 'MKT',       label: 'Marketing',          dot: AREA_COLORS.MKT,       count: gastos.filter(g => g.area === 'MKT').length },
            { value: 'COMERCIAL', label: 'Comercial',          dot: AREA_COLORS.COMERCIAL, count: gastos.filter(g => g.area === 'COMERCIAL').length },
            { value: 'RRHH',      label: 'RRHH',               dot: AREA_COLORS.RRHH,      count: gastos.filter(g => g.area === 'RRHH').length },
            { value: 'GE',        label: 'Gastos generales',   dot: AREA_COLORS.GE,        count: gastos.filter(g => g.area === 'GE').length },
          ]} />
        <Select label="Período" value={periodo} onChange={handlePeriodoChange} w="w-48"
          options={periodos} />
      </div>

      <Card pad="p-0">
        <table className="w-full text-[12.5px]">
          <thead className="bg-slate-50/60">
            <tr className="text-[10px] uppercase tracking-[0.1em] text-slate-500 text-left">
              <th className="font-medium py-3 px-5">ID</th>
              <th className="font-medium">Fecha</th>
              <th className="font-medium">Área</th>
              <th className="font-medium">Descripción</th>
              <th className="font-medium text-right">Monto</th>
              <th className="font-medium">Comprobante</th>
              <th className="font-medium px-3"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(g => (
              <tr key={g.id} className="border-t border-slate-100 tr-hover cursor-pointer">
                <td className="py-3.5 px-5 font-mono text-[11.5px] text-slate-500">{g.id}</td>
                <td className="text-slate-600 font-mono text-[11.5px]">{g.fecha}</td>
                <td>
                  <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium" style={{ background: AREA_COLORS[g.area] + '15', color: AREA_COLORS[g.area] }}>
                    {g.area}
                  </span>
                </td>
                <td className="text-ink">{g.desc}</td>
                <td className="text-right font-mono text-ink">
                  {g.moneda === 'ARS' ? ARS(g.monto) : USD(g.monto)}
                </td>
                <td>
                  {g.comp ? (
                    <span className="inline-flex items-center gap-1.5 text-[11.5px] text-slate-600 hover:text-ink">
                      <I.Doc size={13} />{g.comp.split('/').pop()}
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1.5 text-[11.5px] text-rose-700"><I.X size={13} />Sin comprobante</span>
                  )}
                </td>
                <td className="px-3 text-slate-400">
                  <button
                    onClick={(e) => { e.stopPropagation(); setEditItem(g); }}
                    className="p-1 rounded hover:bg-slate-100 transition-colors">
                    <I.More size={14} />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && <Empty title="Sin gastos" sub="Ajustá los filtros o cargá un nuevo gasto." />}
      </Card>

      {openNew  && <GastoModal onClose={() => setOpenNew(false)} onSaved={onCreated} />}
      {editItem && <GastoModal gasto={editItem} onClose={() => setEditItem(null)} onSaved={onUpdated} />}
    </div>
  );
}

// ── Modal unificado: crear y editar gastos ────────────────────────────────
function GastoModal({ gasto, onClose, onSaved }) {
  const isEdit = !!gasto;
  const today  = new Date().toISOString().slice(0, 10);
  const inputRef = useRef(null);

  const [categoria,    setCategoria]    = useState(gasto?.categoria    || 'GASTO_OPERATIVO');
  const [periodicidad, setPeriodicidad] = useState(gasto?.periodicidad || 'VARIABLE');
  const [moneda,       setMoneda]       = useState(gasto?.moneda       || 'ARS');
  const [monto,        setMonto]        = useState(gasto ? String(gasto.monto) : '');
  const [descripcion,  setDescripcion]  = useState(gasto?.desc         || '');
  const [fecha,        setFecha]        = useState(gasto?.fecha        || today);
  const [notas,        setNotas]        = useState(gasto?.notas || '');
  const [file,         setFile]         = useState(null);
  const [drag,         setDrag]         = useState(false);
  const [usuarioId,    setUsuarioId]    = useState(gasto?.usuarioId    || '');
  const [usuarios,     setUsuarios]     = useState([]);
  const [saving,       setSaving]       = useState(false);
  const [err,          setErr]          = useState(null);

  // Fetch empleados cuando categoria === SUELDO
  useEffect(() => {
    if (categoria === 'SUELDO' && usuarios.length === 0) {
      fetch(`${API_BASE}/api/usuarios`, { credentials: 'include' })
        .then(r => r.json())
        .then(data => setUsuarios(Array.isArray(data) ? data.filter(u => u.activo) : []))
        .catch(e => console.error('[gasto.usuarios]', e));
    }
  }, [categoria]);

  const submit = () => {
    if (!descripcion.trim())                                { setErr('Ingresá una descripción.'); return; }
    if (!monto || isNaN(Number(monto)) || Number(monto) <= 0) { setErr('Ingresá un monto válido.'); return; }
    if (!fecha)                                             { setErr('Seleccioná una fecha.'); return; }
    if (categoria === 'SUELDO' && !usuarioId)               { setErr('Seleccioná el empleado para el sueldo.'); return; }
    setErr(null);
    setSaving(true);

    const url    = isEdit ? `${API_BASE}/api/finanzas/${gasto.id}` : `${API_BASE}/api/finanzas`;
    const method = isEdit ? 'PUT' : 'POST';

    if (file) {
      // multipart/form-data si hay comprobante
      const fd = new FormData();
      fd.append('tipo',        'EGRESO');
      fd.append('periodicidad', periodicidad);
      fd.append('categoria',    categoria);
      fd.append('monto',        String(Number(monto)));
      fd.append('descripcion',  descripcion.trim());
      fd.append('fecha',        fecha);
      fd.append('moneda',       moneda);
      if (notas.trim())  fd.append('notas',      notas.trim());
      if (usuarioId)     fd.append('usuarioId',  usuarioId);
      fd.append('comprobante', file);

      fetch(url, { method, credentials: 'include', body: fd })
        .then(r => r.json())
        .then(handleResponse)
        .catch(handleError);
    } else {
      fetch(url, {
        method,
        credentials: 'include',
        headers:     { 'Content-Type': 'application/json' },
        body:        JSON.stringify({
          tipo:        'EGRESO',
          periodicidad,
          categoria,
          monto:       Number(monto),
          descripcion: descripcion.trim(),
          fecha,
          moneda,
          notas:       notas.trim() || undefined,
          usuarioId:   usuarioId   || undefined,
        }),
      })
        .then(r => r.json())
        .then(handleResponse)
        .catch(handleError);
    }
  };

  const handleResponse = (data) => {
    if (data.error) { setErr(data.error); setSaving(false); return; }
    onSaved(adaptarGasto(data));
  };
  const handleError = (e) => {
    console.error('[gasto.save]', e);
    setErr('Error al guardar gasto.');
    setSaving(false);
  };

  return (
    <div className="fixed inset-0 z-30 flex items-center justify-center p-6">
      <div className="absolute inset-0 bg-ink/40 backdrop-blur-[2px]" onClick={onClose} />
      <div className="relative bg-white rounded-md shadow-pop w-[680px] max-h-[88vh] flex flex-col fade-in">
        <div className="px-7 py-5 border-b border-slate-100 flex items-center justify-between">
          <div>
            <div className="text-[10px] uppercase tracking-[0.14em] text-slate-400">
              {isEdit ? 'Editar registro' : 'Nuevo registro'} · Finanzas
            </div>
            <h2 className="font-serif text-[24px] leading-none text-ink mt-1">
              {isEdit ? 'Editar gasto' : 'Cargar gasto'}
            </h2>
          </div>
          <button onClick={onClose} className="p-1.5 rounded hover:bg-slate-100 text-slate-500"><I.X size={16} /></button>
        </div>

        <div className="px-7 py-6 overflow-y-auto flex-1">
          <div className="grid grid-cols-2 gap-5">
            <div>
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Fecha</label>
              <input type="date" value={fecha} onChange={e => setFecha(e.target.value)}
                className="mt-1.5 w-full px-3 py-2 text-[13px] border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
            </div>
            <div>
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Categoría</label>
              <select value={categoria} onChange={e => setCategoria(e.target.value)}
                className="mt-1.5 w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400">
                {GASTO_CATS_API.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
              </select>
            </div>

            {/* Selector de empleado — solo cuando categoria === SUELDO */}
            {categoria === 'SUELDO' && (
              <div className="col-span-2">
                <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">
                  Empleado <span className="text-rose-500">*</span>
                </label>
                <select value={usuarioId} onChange={e => setUsuarioId(e.target.value)}
                  className="mt-1.5 w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400">
                  <option value="">— Seleccioná empleado —</option>
                  {usuarios.map(u => <option key={u.id} value={u.id}>{u.nombre} {u.apellido} · {u.rol}</option>)}
                </select>
              </div>
            )}

            <div>
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Periodicidad</label>
              <div className="mt-1.5 inline-flex border border-slate-200 rounded overflow-hidden">
                {['FIJO', 'VARIABLE'].map(p => (
                  <button key={p} onClick={() => setPeriodicidad(p)}
                    className={`px-4 py-2 text-[12px] font-medium transition-colors ${periodicidad === p ? 'bg-slate-700 text-white' : 'bg-white text-slate-500 hover:bg-slate-50'}`}>
                    {p === 'FIJO' ? 'Fijo' : 'Variable'}
                  </button>
                ))}
              </div>
            </div>

            <div className="col-span-2">
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Descripción</label>
              <input value={descripcion} onChange={e => setDescripcion(e.target.value)}
                placeholder="Ej. Honorarios contables mayo"
                className="mt-1.5 w-full px-3 py-2 text-[13px] border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
            </div>

            <div>
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Monto</label>
              <div className="mt-1.5 flex">
                <input value={monto} onChange={e => setMonto(e.target.value.replace(/[^0-9.]/g, ''))}
                  placeholder="0" className="flex-1 px-3 py-2 text-[13px] border border-slate-200 rounded-l font-mono focus:outline-none focus:border-slate-400" />
                <div className="inline-flex border border-l-0 border-slate-200 rounded-r overflow-hidden">
                  {['ARS', 'USD'].map(m => (
                    <button key={m} onClick={() => setMoneda(m)}
                      className={`px-3 text-[11.5px] font-medium ${moneda === m ? 'bg-slate-700 text-white' : 'bg-white text-slate-500 hover:bg-slate-50'}`}>{m}</button>
                  ))}
                </div>
              </div>
            </div>

            <div className="col-span-2">
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">
                Comprobante <span className="text-slate-400 font-normal">(opcional)</span>
              </label>
              <div
                onDragOver={e => { e.preventDefault(); setDrag(true); }}
                onDragLeave={() => setDrag(false)}
                onDrop={e => { e.preventDefault(); setDrag(false); if (e.dataTransfer.files[0]) setFile(e.dataTransfer.files[0]); }}
                onClick={() => inputRef.current?.click()}
                className={`mt-1.5 border border-dashed rounded p-6 text-center cursor-pointer transition-colors ${drag ? 'border-slate-400 bg-slate-50' : file ? 'border-emerald-300 bg-emerald-50/40' : 'border-slate-200 hover:border-slate-300'}`}>
                <input ref={inputRef} type="file" className="hidden" onChange={e => setFile(e.target.files?.[0])} />
                {file ? (
                  <div className="flex items-center justify-center gap-2 text-[13px] text-emerald-800">
                    <I.Check size={16} sw={2} /> {file.name}
                  </div>
                ) : (
                  <>
                    <I.Upload size={20} className="mx-auto text-slate-400" />
                    <div className="text-[13px] text-ink mt-2 font-medium">Arrastrá el comprobante</div>
                    <div className="text-[11px] text-slate-500 mt-0.5">o hacé click para seleccionar · PDF, JPG, PNG</div>
                  </>
                )}
              </div>
            </div>

            <div className="col-span-2">
              <label className="text-[11px] uppercase tracking-[0.12em] text-slate-500 font-medium">Notas (opcional)</label>
              <textarea rows={2} value={notas} onChange={e => setNotas(e.target.value)}
                placeholder="Detalle adicional…" className="mt-1.5 w-full px-3 py-2 text-[13px] border border-slate-200 rounded focus:outline-none focus:border-slate-400 resize-none" />
            </div>
          </div>

          {err && <div className="mt-4 text-[12px] text-rose-700 bg-rose-50 border border-rose-200 rounded px-3 py-2">{err}</div>}
        </div>

        <div className="px-7 py-4 border-t border-slate-100 flex items-center gap-3 bg-canvas">
          <div className="flex-1 text-[11px] text-slate-500">
            {isEdit ? 'Los cambios se aplicarán de inmediato.' : 'Se registrará el gasto inmediatamente.'}
          </div>
          <Button variant="ghost" size="md" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" size="md" onClick={submit} disabled={saving}>
            {saving ? 'Guardando…' : (isEdit ? 'Guardar cambios' : 'Guardar')}
          </Button>
        </div>
      </div>
    </div>
  );
}

window.Gastos        = Gastos;
window.FormaPagoChip = FormaPagoChip;
window.AREA_COLORS   = AREA_COLORS;
