// ─── Ingresos (internos, fuera de operaciones) ─────────────────────────────

const INGRESO_CATS_API = [
  { value: 'ALQUILER',    label: 'Alquiler' },
  { value: 'MENSUALIDAD', label: 'Mensualidad' },
  { value: 'COMISION',    label: 'Comisión' },
  { value: 'OTRO',        label: 'Otro' },
];

function adaptarIngreso(m) {
  return {
    id:           m.id,
    fecha:        m.fecha ? m.fecha.slice(0, 10) : '',
    concepto:     m.descripcion,
    categoria:    m.categoria,
    periodicidad: m.periodicidad,
    monto:        Number(m.monto),
    moneda:       m.moneda,
    notas:        m.notas ?? '',
  };
}

function generarPeriodos() {
  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;
}

function periodoDates(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 Ingresos() {
  const periodos       = React.useMemo(generarPeriodos, []);
  const defaultPeriodo = periodos[0].value;

  const [cat, setCat]         = useState('Todas');
  const [periodo, setPeriodo] = useState(defaultPeriodo);
  const [openNew, setOpenNew] = useState(false);
  const [editItem, setEditItem] = useState(null);
  const [ingresos, setIngresos] = 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=INGRESO&desde=${desde}&hasta=${hasta}`, { credentials: 'include' })
      .then(r => r.json())
      .then(json => {
        setIngresos((Array.isArray(json) ? json : (json.data ?? [])).map(adaptarIngreso));
        setLoading(false);
      })
      .catch(err => {
        console.error('[ingresos fetch]', err);
        setError('Error al cargar ingresos.');
        setLoading(false);
      });
  };

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

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

  const filtered = useMemo(() => ingresos.filter(i =>
    cat === 'Todas' || i.categoria === cat
  ), [ingresos, cat]);

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

  const columns = [
    { key: 'id',       label: 'ID' },
    { key: 'fecha',    label: 'Fecha' },
    { key: 'concepto', label: 'Concepto' },
    { key: 'categoria',label: 'Categoría' },
    { key: 'monto',    label: 'Monto' },
    { key: 'moneda',   label: 'Moneda' },
    { key: 'notas',    label: 'Notas' },
  ];

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

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

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

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Finanzas', 'Ingresos']}
        title="Ingresos"
        sub={`Ingresos internos · fuera de operaciones · no aplican comisión a brokers`}
        actions={
          <>
            <ExportButton filename={`lanven-ingresos-${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 ingreso</Button>
          </>
        }
      />

      {/* Totales strip */}
      <div className="grid grid-cols-3 gap-4 mb-5">
        <div className="bg-white rounded-md border border-slate-100 shadow-card p-5">
          <div className="text-[10px] uppercase tracking-[0.13em] text-slate-500 font-medium">Total ingresos · mes</div>
          <div className="font-mono text-[22px] text-emerald-700 leading-none mt-2">{ARS(totalARS)}</div>
          <div className="text-[12px] text-slate-500 font-mono mt-1">+ {USD(totalUSD)}</div>
        </div>
        <div className="bg-white rounded-md border border-slate-100 shadow-card p-5">
          <div className="text-[10px] uppercase tracking-[0.13em] text-slate-500 font-medium">Por categoría · top</div>
          <div className="mt-3 space-y-1.5">
            {INGRESO_CATS_API.slice(0, 3).map(c => {
              const n = ingresos.filter(i => i.categoria === c.value).length;
              const m = ingresos.filter(i => i.categoria === c.value).reduce((s, i) => s + (i.moneda === 'ARS' ? i.monto : i.monto * 1180), 0);
              return (
                <div key={c.value} className="flex items-center justify-between text-[12px]">
                  <span className="text-slate-600">{c.label}</span>
                  <span className="font-mono text-slate-700">{ARS_C(m)} <span className="text-slate-400 text-[10px]">· {n}</span></span>
                </div>
              );
            })}
          </div>
        </div>
        <div className="bg-canvas rounded-md border border-slate-100 p-5 flex items-start gap-3">
          <span className="w-6 h-6 rounded-full bg-gold/30 text-gold-deep flex items-center justify-center flex-shrink-0 mt-0.5">
            <I.Check size={14} sw={2.5} />
          </span>
          <div>
            <div className="text-[12px] text-ink font-medium">No aplican % comisión</div>
            <div className="text-[11.5px] text-slate-500 mt-1 leading-snug">
              Los ingresos cargados acá <b>no</b> distribuyen comisión a brokers ni acumulan m² alquilados. Son movimientos internos como alquiler de cochera u oficina.
            </div>
          </div>
        </div>
      </div>

      <div className="flex items-center gap-2.5 mb-4 flex-wrap">
        <Select label="Categoría" value={cat} onChange={setCat} w="w-52"
          options={[
            { value: 'Todas', label: 'Todas las categorías', count: ingresos.length },
            ...INGRESO_CATS_API.map(c => ({ value: c.value, label: c.label, count: ingresos.filter(i => i.categoria === c.value).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">Concepto</th>
              <th className="font-medium">Categoría</th>
              <th className="font-medium text-right">Monto</th>
              <th className="font-medium">Notas</th>
              <th className="font-medium px-3"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(i => (
              <tr key={i.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">{i.id}</td>
                <td className="text-slate-600 font-mono text-[11.5px]">{i.fecha}</td>
                <td className="text-ink">{i.concepto}</td>
                <td><span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium bg-emerald-50 text-emerald-800">{i.categoria}</span></td>
                <td className="text-right font-mono text-emerald-700">+ {i.moneda === 'ARS' ? ARS(i.monto) : USD(i.monto)}</td>
                <td className="text-slate-500 text-[11.5px] truncate max-w-[180px]">{i.notas || '—'}</td>
                <td className="px-3 text-slate-400">
                  <button
                    onClick={(e) => { e.stopPropagation(); setEditItem(i); }}
                    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 ingresos" sub="Ajustá los filtros o cargá un nuevo ingreso." />}
      </Card>

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

// ── Modal unificado: crear y editar ingresos ───────────────────────────────
function IngresoModal({ ingreso, onClose, onSaved }) {
  const isEdit = !!ingreso;
  const today  = new Date().toISOString().slice(0, 10);

  const [cat,          setCat]          = useState(ingreso?.categoria    || 'ALQUILER');
  const [periodicidad, setPeriodicidad] = useState(ingreso?.periodicidad || 'FIJO');
  const [moneda,       setMoneda]       = useState(ingreso?.moneda       || 'ARS');
  const [monto,        setMonto]        = useState(ingreso ? String(ingreso.monto) : '');
  const [descripcion,  setDescripcion]  = useState(ingreso?.concepto     || '');
  const [fecha,        setFecha]        = useState(ingreso?.fecha        || today);
  const [notas,        setNotas]        = useState(ingreso?.notas        || '');
  const [saving,       setSaving]       = useState(false);
  const [err,          setErr]          = useState(null);

  const submit = () => {
    if (!descripcion.trim())                                { setErr('Ingresá un concepto.'); return; }
    if (!monto || isNaN(Number(monto)) || Number(monto) <= 0) { setErr('Ingresá un monto válido.'); return; }
    if (!fecha)                                             { setErr('Seleccioná una fecha.'); return; }
    setErr(null);
    setSaving(true);

    const body = {
      tipo:        'INGRESO',
      periodicidad,
      categoria:   cat,
      monto:       Number(monto),
      descripcion: descripcion.trim(),
      fecha,
      moneda,
      notas:       notas.trim() || undefined,
    };

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

    fetch(url, {
      method,
      credentials: 'include',
      headers:     { 'Content-Type': 'application/json' },
      body:        JSON.stringify(body),
    })
      .then(r => r.json())
      .then(data => {
        if (data.error) { setErr(data.error); setSaving(false); return; }
        onSaved(adaptarIngreso(data));
      })
      .catch(e => {
        console.error('[ingreso.save]', e);
        setErr('Error al guardar ingreso.');
        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 ingreso' : 'Cargar ingreso'}
            </h2>
          </div>
          <button onClick={onClose} className="p-1.5 rounded hover:bg-slate-100 text-slate-500"><I.X size={16} /></button>
        </div>

        {!isEdit && (
          <div className="px-7 py-3 bg-amber-50/50 border-b border-amber-100 flex items-start gap-2.5 text-[11.5px] text-amber-900">
            <I.Bell size={13} className="mt-0.5 flex-shrink-0" />
            <div>Los ingresos cargados acá no distribuyen comisión a brokers ni computan m² alquilados. Si esto corresponde a una venta o alquiler de cliente, cargalo desde <b>Operaciones</b>.</div>
          </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 label="" value={cat} onChange={setCat} w="w-full"
                options={INGRESO_CATS_API.map(c => ({ value: c.value, label: c.label }))} />
            </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">Concepto</label>
              <input value={descripcion} onChange={e => setDescripcion(e.target.value)}
                placeholder="Ej. Alquiler cochera Olleros 2280"
                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">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.' : 'Quedará disponible 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 ingreso')}
          </Button>
        </div>
      </div>
    </div>
  );
}

window.Ingresos = Ingresos;
