// ─── Movimientos entre cajas ────────────────────────────────────────────────

const API =
  (location.hostname === 'localhost' || location.hostname === '127.0.0.1')
    ? 'http://localhost:3001'
    : 'https://api.lanven.com.ar';

// Metadatos de presentación por nombre ENUM (espeja cajas.jsx)
const CAJA_META_MOV = {
  CAJA_CHICA:  { label: 'Caja Chica',    color: '#10b981' },
  CAJA_ALVARO: { label: 'Caja Álvaro',   color: '#6366f1' },
  CAJA_MAY:    { label: 'Caja May',       color: '#f59e0b' },
  BANCO:       { label: 'Cuenta Bancaria', color: '#3b82f6' },
};

function adaptarCajaMov(c) {
  const meta = CAJA_META_MOV[c.nombre] ?? { label: c.nombre, color: '#677A88' };
  return {
    id:       c.id,          // cuid real de BD — se usa para post y filtros
    nombre:   meta.label,
    color:    meta.color,
    saldoARS: Number(c.saldoARS),
    saldoUSD: Number(c.saldoUSD),
  };
}

function adaptarTransferencia(t) {
  return {
    id:      t.id,
    fecha:   t.creadoEn.slice(0, 10),
    origen:  t.cajaOrigenId,
    destino: t.cajaDestinoId,
    monto_o: Number(t.montoOrigen),
    mon_o:   t.monedaOrigen,
    tc:      Number(t.tipoCambio) !== 1 ? Number(t.tipoCambio) : null,
    monto_d: Number(t.montoDestino),
    mon_d:   t.monedaDestino,
    concepto: t.concepto ?? '',
    user:    t.usuario ? `${t.usuario.nombre} ${t.usuario.apellido ?? ''}`.trim() : '—',
  };
}

function Movimientos() {
  const [origenFiltro,  setOrigenFiltro]  = useState('todas');
  const [destinoFiltro, setDestinoFiltro] = useState('todas');
  const [openNew, setOpenNew]   = useState(false);
  const [cajasVivas, setCajasVivas]       = useState([]);
  const [cajasPorId, setCajasPorId]       = useState({});
  const [movimientos, setMovimientos]     = useState([]);
  const [loadingMov,  setLoadingMov]      = useState(true);

  function cargarDatos() {
    setLoadingMov(true);
    Promise.all([
      fetch(`${API}/api/cajas`,          { credentials: 'include' }).then(r => r.json()),
      fetch(`${API}/api/cajas/transferencias`, { credentials: 'include' }).then(r => r.json()),
    ])
      .then(([cajasRaw, transRaw]) => {
        const adapted = (Array.isArray(cajasRaw) ? cajasRaw : []).map(adaptarCajaMov);
        setCajasVivas(adapted);
        setCajasPorId(Object.fromEntries(adapted.map(c => [c.id, c])));
        setMovimientos((Array.isArray(transRaw) ? transRaw : []).map(adaptarTransferencia));
        setLoadingMov(false);
      })
      .catch(err => {
        console.error('[movimientos fetch]', err);
        setLoadingMov(false);
      });
  }

  useEffect(() => { cargarDatos(); }, []);

  const filtered = useMemo(() => movimientos.filter(m =>
    (origenFiltro  === 'todas' || m.origen  === origenFiltro) &&
    (destinoFiltro === 'todas' || m.destino === destinoFiltro)
  ), [movimientos, origenFiltro, destinoFiltro]);

  const columns = [
    { key: 'id', label: 'ID' },
    { key: 'fecha', label: 'Fecha' },
    { label: 'Origen',  value: m => cajasPorId[m.origen]?.nombre },
    { label: 'Destino', value: m => cajasPorId[m.destino]?.nombre },
    { label: 'Monto origen',  value: m => m.monto_o },
    { key: 'mon_o', label: 'Moneda origen' },
    { key: 'tc',    label: 'TC' },
    { label: 'Monto destino', value: m => m.monto_d },
    { key: 'mon_d', label: 'Moneda destino' },
    { key: 'concepto', label: 'Concepto' },
    { key: 'user',     label: 'Usuario' },
  ];

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Finanzas', 'Movimientos']}
        title="Movimientos entre cajas"
        sub={`${filtered.length} movimientos · traspasos internos con o sin conversión de moneda`}
        actions={
          <>
            <ExportButton filename={`lanven-movimientos-${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 movimiento</Button>
          </>
        }
      />

      <div className="flex items-center gap-2.5 mb-4 flex-wrap">
        <Select label="Desde" value={origenFiltro} onChange={setOrigenFiltro} w="w-48"
          options={[
            { value: 'todas', label: 'Cualquier caja' },
            ...cajasVivas.map(c => ({ value: c.id, label: c.nombre, dot: c.color, count: movimientos.filter(m => m.origen === c.id).length })),
          ]} />
        <I.Arrow size={14} className="text-slate-400" />
        <Select label="Hacia" value={destinoFiltro} onChange={setDestinoFiltro} w="w-48"
          options={[
            { value: 'todas', label: 'Cualquier caja' },
            ...cajasVivas.map(c => ({ value: c.id, label: c.nombre, dot: c.color, count: movimientos.filter(m => m.destino === c.id).length })),
          ]} />
        <Select label="Período" value="may-2026" onChange={() => {}} w="w-44"
          options={[
            { value: 'may-2026', label: 'Mayo 2026' },
            { value: 'abr-2026', label: 'Abril 2026' },
            { value: 'q2-2026',  label: 'Q2 2026' },
            { value: 'ytd',      label: 'Año a la fecha' },
          ]} />
      </div>

      {loadingMov && <div className="p-8 text-slate-500">Cargando movimientos…</div>}

      {!loadingMov && (
        <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">Origen</th>
                <th className="font-medium text-right">Monto</th>
                <th className="font-medium text-center px-3"></th>
                <th className="font-medium">Destino</th>
                <th className="font-medium text-right">Monto</th>
                <th className="font-medium text-right">TC</th>
                <th className="font-medium">Concepto</th>
                <th className="font-medium">Por</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(m => {
                const cajO = cajasPorId[m.origen]  ?? {};
                const cajD = cajasPorId[m.destino] ?? {};
                return (
                  <tr key={m.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">{m.id}</td>
                    <td className="text-slate-600 font-mono text-[11.5px]">{m.fecha.slice(5)}</td>
                    <td className="text-slate-700 text-[12px]">
                      <span className="inline-flex items-center gap-1.5">
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: cajO.color ?? '#677A88' }} />
                        {cajO.nombre ?? '—'}
                      </span>
                    </td>
                    <td className="text-right font-mono text-rose-700">− {m.mon_o === 'ARS' ? ARS(m.monto_o) : USD(m.monto_o)}</td>
                    <td className="text-center px-3 text-slate-300"><I.Arrow size={14} /></td>
                    <td className="text-slate-700 text-[12px]">
                      <span className="inline-flex items-center gap-1.5">
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: cajD.color ?? '#677A88' }} />
                        {cajD.nombre ?? '—'}
                      </span>
                    </td>
                    <td className="text-right font-mono text-emerald-700">+ {m.mon_d === 'ARS' ? ARS(m.monto_d) : USD(m.monto_d)}</td>
                    <td className="text-right font-mono text-slate-500 text-[11.5px]">{m.tc ? `$${NUM(m.tc)}` : '—'}</td>
                    <td className="text-ink text-[12px] max-w-[220px] truncate" title={m.concepto}>{m.concepto}</td>
                    <td className="text-slate-600 text-[12px] pr-4">{m.user}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {filtered.length === 0 && <Empty title="Sin movimientos" sub="Ajustá los filtros o creá un nuevo traspaso." />}
        </Card>
      )}

      {openNew && (
        <NuevoMovimientoModal
          cajas={cajasVivas}
          cajasPorId={cajasPorId}
          onClose={() => setOpenNew(false)}
          onSuccess={() => { cargarDatos(); setOpenNew(false); }}
        />
      )}
    </div>
  );
}

function NuevoMovimientoModal({ cajas, cajasPorId, onClose, onSuccess }) {
  const [origen,   setOrigen]   = useState(() => cajas[0]?.id ?? '');
  const [destino,  setDestino]  = useState(() => cajas[1]?.id ?? '');
  const [monedaO,  setMonedaO]  = useState('USD');
  const [monedaD,  setMonedaD]  = useState('ARS');
  const [montoO,   setMontoO]   = useState('2000');
  const [tc,       setTc]       = useState('1180.50');
  const [concepto, setConcepto] = useState('');
  const [loading,  setLoading]  = useState(false);
  const [error,    setError]    = useState(null);

  const cruzaMoneda = monedaO !== monedaD;
  const montoD = useMemo(() => {
    const n = parseFloat(montoO) || 0;
    if (!cruzaMoneda) return n;
    if (monedaO === 'USD' && monedaD === 'ARS') return n * (parseFloat(tc) || 0);
    if (monedaO === 'ARS' && monedaD === 'USD') return n / (parseFloat(tc) || 1);
    return n;
  }, [montoO, tc, monedaO, monedaD, cruzaMoneda]);

  async function handleConfirmar() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${API}/api/cajas/transferencia`, {
        method:      'POST',
        credentials: 'include',
        headers:     { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          cajaOrigenId:  origen,
          cajaDestinoId: destino,
          montoOrigen:   parseFloat(montoO),
          monedaOrigen:  monedaO,
          tipoCambio:    parseFloat(tc) || 1,
          montoDestino:  parseFloat(montoD),
          monedaDestino: monedaD,
          concepto:      concepto || null,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? 'Error al guardar el movimiento.');
        return;
      }
      onSuccess();
    } catch {
      setError('Error de conexión con el servidor.');
    } finally {
      setLoading(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-[760px] 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">Nuevo registro · Finanzas</div>
            <h2 className="font-serif text-[24px] leading-none text-ink mt-1">Movimiento entre cajas</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-[1fr_auto_1fr] gap-5 items-stretch">
            {/* Origen */}
            <div className="bg-canvas border border-slate-100 rounded-md p-5">
              <div className="text-[10px] uppercase tracking-[0.14em] text-rose-700 font-semibold mb-3">Origen · sale</div>
              <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500">Caja / Cuenta</label>
              <div className="mt-1.5 space-y-1">
                {cajas.map(c => (
                  <button key={c.id} onClick={() => setOrigen(c.id)}
                    className={`w-full text-left px-3 py-2 rounded border transition-colors flex items-center gap-2 ${origen === c.id ? 'border-slate-700 bg-white' : 'bg-white border-slate-200 hover:border-slate-300'}`}>
                    <span className="w-1.5 h-1.5 rounded-full" style={{ background: c.color }} />
                    <span className="text-[12px] text-ink flex-1">{c.nombre}</span>
                    <span className="text-[10px] text-slate-400 font-mono">{ARS_C(c.saldoARS)} · {USD_C(c.saldoUSD)}</span>
                  </button>
                ))}
              </div>
              <div className="mt-4">
                <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500">Monto</label>
                <div className="mt-1.5 flex">
                  <input value={montoO} onChange={e => setMontoO(e.target.value)} className="flex-1 px-3 py-2 text-[13px] border border-slate-200 rounded-l font-mono bg-white focus:outline-none focus:border-slate-400" />
                  <div className="inline-flex border border-l-0 border-slate-200 rounded-r overflow-hidden bg-white">
                    {['ARS', 'USD'].map(m => (
                      <button key={m} onClick={() => setMonedaO(m)}
                        className={`px-3 text-[11.5px] font-medium ${monedaO === m ? 'bg-slate-700 text-white' : 'text-slate-500 hover:bg-slate-50'}`}>{m}</button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Connector */}
            <div className="flex flex-col items-center justify-center px-1 self-stretch">
              <div className="w-px flex-1 bg-slate-200" />
              <div className="my-2 w-9 h-9 rounded-full bg-gold flex items-center justify-center text-slate-900">
                <I.Arrow size={16} sw={2} />
              </div>
              <div className="w-px flex-1 bg-slate-200" />
            </div>

            {/* Destino */}
            <div className="bg-canvas border border-slate-100 rounded-md p-5">
              <div className="text-[10px] uppercase tracking-[0.14em] text-emerald-700 font-semibold mb-3">Destino · entra</div>
              <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500">Caja / Cuenta</label>
              <div className="mt-1.5 space-y-1">
                {cajas.map(c => (
                  <button key={c.id} disabled={c.id === origen} onClick={() => setDestino(c.id)}
                    className={`w-full text-left px-3 py-2 rounded border transition-colors flex items-center gap-2 ${destino === c.id ? 'border-slate-700 bg-white' : 'bg-white border-slate-200 hover:border-slate-300'} ${c.id === origen ? 'opacity-30 cursor-not-allowed' : ''}`}>
                    <span className="w-1.5 h-1.5 rounded-full" style={{ background: c.color }} />
                    <span className="text-[12px] text-ink flex-1">{c.nombre}</span>
                    <span className="text-[10px] text-slate-400 font-mono">{ARS_C(c.saldoARS)} · {USD_C(c.saldoUSD)}</span>
                  </button>
                ))}
              </div>
              <div className="mt-4">
                <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500">Moneda recibida</label>
                <div className="mt-1.5 inline-flex border border-slate-200 rounded overflow-hidden bg-white">
                  {['ARS', 'USD'].map(m => (
                    <button key={m} onClick={() => setMonedaD(m)}
                      className={`px-3 py-2 text-[11.5px] font-medium ${monedaD === m ? 'bg-slate-700 text-white' : 'text-slate-500 hover:bg-slate-50'}`}>{m}</button>
                  ))}
                </div>
                <div className="mt-3 font-mono text-[20px] text-emerald-700 leading-none">
                  + {monedaD === 'ARS' ? ARS(Math.round(montoD)) : USD(Math.round(montoD))}
                </div>
                <div className="text-[10px] text-slate-400 mt-1">se acreditará en {cajasPorId[destino]?.nombre ?? '—'}</div>
              </div>
            </div>
          </div>

          {/* TC + meta */}
          <div className="mt-5 grid grid-cols-3 gap-4">
            <div className={`p-4 rounded border ${cruzaMoneda ? 'border-gold/40 bg-gold/5' : 'border-slate-100 bg-canvas opacity-60'}`}>
              <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500 font-medium flex items-center gap-1.5">
                Tipo de cambio
                {cruzaMoneda && <span className="text-gold-deep font-mono normal-case">· requerido</span>}
              </label>
              <input value={tc} onChange={e => setTc(e.target.value)} disabled={!cruzaMoneda}
                className="mt-1.5 w-full px-3 py-2 text-[13px] border border-slate-200 rounded font-mono bg-white focus:outline-none focus:border-slate-400 disabled:bg-slate-50" />
              <div className="text-[10px] text-slate-400 mt-1">{cruzaMoneda ? `1 USD = $${tc} ARS` : 'sin conversión de moneda'}</div>
            </div>
            <div className="col-span-2 p-4 rounded border border-slate-100 bg-canvas">
              <label className="text-[10px] uppercase tracking-[0.12em] text-slate-500 font-medium">Concepto</label>
              <input
                value={concepto}
                onChange={e => setConcepto(e.target.value)}
                placeholder="Ej. Depósito bancario · reposición caja"
                className="mt-1.5 w-full px-3 py-2 text-[13px] border border-slate-200 rounded bg-white focus:outline-none focus:border-slate-400" />
            </div>
          </div>
        </div>

        <div className="px-7 py-4 border-t border-slate-100 flex items-center gap-3 bg-white">
          <div className="flex-1">
            {error && <div className="text-rose-600 text-[11.5px]">{error}</div>}
            {!error && <div className="text-[11.5px] text-slate-500">Quedará registrado en <b>Movimientos</b> · actualiza saldos de origen y destino.</div>}
          </div>
          <Button variant="ghost" size="md" onClick={onClose}>Cancelar</Button>
          <Button variant="gold" size="md" disabled={origen === destino || loading} onClick={handleConfirmar}>
            {loading ? 'Guardando…' : 'Confirmar traspaso'}
          </Button>
        </div>
      </div>
    </div>
  );
}

window.Movimientos = Movimientos;
