// pages/FinanceiroPage.jsx — real data

// 2ª via de boleto / comprovante — arquivos vindos do sistema de gerenciamento.
const boletoUrl = (parcela, dl) =>
  "/portal-cliente/api/financeiro/boleto?parcela=" + encodeURIComponent(parcela) + (dl ? "&dl=1" : "");

function FinanceiroPage() {
  const entry = FIN.entry;
  const installments = FIN.installments || [];
  const paid = installments.filter(i => i.status === "paid").reduce((a, b) => a + b.amount, 0) + (entry?.status === "paid" ? entry.amount : 0);
  const pending = Math.max(0, FIN.total - paid);
  const paidCount = installments.filter(i => i.status === "paid").length + (entry?.status === "paid" ? 1 : 0);
  const pendingCount = installments.filter(i => i.status !== "paid").length + (entry && entry.status !== "paid" ? 1 : 0);
  const nextInstallment = installments.find(i => i.status !== "paid");
  const daysToNext = nextInstallment ? (() => {
    try {
      const d = new Date(String(nextInstallment.due).slice(0,10) + "T12:00:00");
      const today = new Date(); today.setHours(0,0,0,0);
      return Math.max(0, Math.round((d - today) / 86400000));
    } catch { return null; }
  })() : null;

  const statusPill = (s) => {
    if (s === "paid") return <span className="pill green"><I.Check size={11} /> Pago</span>;
    if (s === "upcoming") return <span className="pill amber"><I.Clock size={11} /> Proxima</span>;
    return <span className="pill">Futura</span>;
  };

  // Proxima parcela com 2ª via de boleto disponivel (para o botao do cabecalho)
  const proxBoleto = installments.find(i => i.status !== "paid" && i.boletoDisponivel);
  const entryBoleto = entry && entry.status !== "paid" && entry.boletoDisponivel;

  // Celula "Documento": 2ª via do boleto p/ parcelas em aberto com boleto disponivel.
  // Parcelas pagas nao expoem comprovante (o sistema nao gera esse PDF) → "—".
  const boletoDocCell = (item) => {
    if (item.status === "paid") {
      return <span style={{ color: "#bdbdbd", fontSize: 12 }}>—</span>;
    }
    if (item.boletoDisponivel) {
      const isUpcoming = item.status === "upcoming";
      return (
        <a
          className="btn"
          href={boletoUrl(item.n, 1)}
          download
          style={{
            height: 26,
            padding: "0 8px",
            fontSize: 11,
            textDecoration: "none",
            background: isUpcoming ? "var(--fg)" : "#fff",
            color: isUpcoming ? "#fff" : "var(--fg)",
            borderColor: isUpcoming ? "var(--fg)" : "var(--border-strong)",
          }}
          title="Baixar 2ª via do boleto"
        >
          <I.Download size={12} /> 2ª via
        </a>
      );
    }
    return <span style={{ color: "#bdbdbd", fontSize: 12 }} title="Boleto ainda nao disponivel">—</span>;
  };

  const pct = (v) => FIN.total > 0 ? Math.round((v / FIN.total) * 100) : 0;

  if (FIN.total <= 0 && installments.length === 0) {
    return (
      <div className="page">
        <div className="page-header">
          <div>
            <h1 className="page-title">Financeiro</h1>
            <div className="page-sub">contrato {PROJECT.code}</div>
          </div>
        </div>
        <div className="card" style={{ padding: 32, textAlign: "center", color: "#999" }}>
          Nao existem dados financeiros desta obra. Seu engenheiro cadastra o contrato no sistema e as parcelas aparecem aqui.
        </div>
      </div>
    );
  }

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Financeiro</h1>
          <div className="page-sub">{entry ? "Entrada + " : ""}{installments.length} parcelas · contrato {PROJECT.code}</div>
        </div>
        {(proxBoleto || entryBoleto) && (
          <div className="page-actions">
            <button
              className="btn primary"
              onClick={() => window.open(boletoUrl(proxBoleto ? proxBoleto.n : "entrada"), "_blank")}
              title="Baixar 2ª via do boleto da próxima parcela"
            >
              <I.Download size={14} /> 2ª via boleto
            </button>
          </div>
        )}
      </div>

      <div className="grid grid-4" style={{ marginBottom: 16 }}>
        <div className="kpi">
          <div className="kpi-label">Valor total</div>
          <div className="kpi-value">{fmtBRL(FIN.total)}</div>
          <div className="kpi-foot"><span>contrato integral</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Ja pago</div>
          <div className="kpi-value">{fmtBRL(paid)}</div>
          <div className="bar" style={{ marginTop: 10 }}><span style={{ width: pct(paid) + "%" }} /></div>
          <div className="kpi-foot"><span>{pct(paid)}%</span><span>{paidCount} pagamento{paidCount !== 1 ? "s" : ""}</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">A pagar</div>
          <div className="kpi-value">{fmtBRL(pending)}</div>
          <div className="bar" style={{ marginTop: 10 }}><span style={{ width: pct(pending) + "%" }} /></div>
          <div className="kpi-foot"><span>{pct(pending)}%</span><span>{pendingCount} parcela{pendingCount !== 1 ? "s" : ""}</span></div>
        </div>
        {nextInstallment ? (
          <div className="kpi" style={{ background: "#0A0A0A", color: "#fff", borderColor: "#0A0A0A" }}>
            <div className="kpi-label" style={{ color: "#999" }}>Proxima parcela</div>
            <div className="kpi-value" style={{ color: "#fff" }}>{fmtBRL(nextInstallment.amount)}</div>
            <div className="kpi-delta" style={{ color: "#bdbdbd" }}>parcela #{nextInstallment.n} · vence {fmtDate(nextInstallment.due)}</div>
            <div className="kpi-foot" style={{ borderColor: "#2A2A2A", color: "#999" }}>
              <span>{daysToNext !== null ? ("em " + daysToNext + " dias") : "—"}</span>
              <span>—</span>
            </div>
          </div>
        ) : (
          <div className="kpi">
            <div className="kpi-label">Status</div>
            <div className="kpi-value" style={{ fontSize: 20 }}>Quitado</div>
            <div className="kpi-foot"><span>todas as parcelas pagas</span></div>
          </div>
        )}
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-head">
          <div className="card-title">Cronograma de pagamentos</div>
          <div className="card-sub mono">{installments.length} parcela{installments.length !== 1 ? "s" : ""}{entry ? " + entrada" : ""}</div>
        </div>
        <table className="t">
          <thead>
            <tr>
              <th style={{ width: 40 }}>#</th>
              <th>Descricao</th>
              <th style={{ width: 140 }}>Vencimento</th>
              <th style={{ width: 140 }}>Pagamento</th>
              <th className="right" style={{ width: 150 }}>Valor (R$)</th>
              <th style={{ width: 110 }}>Status</th>
              <th style={{ width: 130 }}>Documento</th>
            </tr>
          </thead>
          <tbody>
            {entry && (
              <tr>
                <td className="mono" style={{ color: "#999" }}>—</td>
                <td style={{ fontWeight: 500 }}>Entrada</td>
                <td className="mono">{entry.date ? fmtDate(entry.date) : "—"}</td>
                <td className="mono">{entry.status === "paid" ? (entry.paidOn ? fmtDate(entry.paidOn) : (entry.date ? fmtDate(entry.date) : "pago")) : "—"}</td>
                <td className="right mono num" style={{ fontWeight: 500 }}>{fmtBRL2(entry.amount)}</td>
                <td>{statusPill(entry.status)}</td>
                <td>{boletoDocCell({ n: "entrada", status: entry.status, boletoDisponivel: entry.boletoDisponivel })}</td>
              </tr>
            )}
            {installments.map(inst => (
              <tr key={inst.n} style={{ opacity: inst.status === "paid" ? 0.75 : 1 }}>
                <td className="mono" style={{ color: "#999" }}>{String(inst.n).padStart(2, "0")}</td>
                <td style={{ fontWeight: 500 }}>{inst.label || ("Parcela " + inst.n + "/" + installments.length)}</td>
                <td className="mono">{fmtDate(inst.due)}</td>
                <td className="mono" style={{ color: inst.paidOn ? "#0A0A0A" : "#bdbdbd" }}>{inst.paidOn ? fmtDate(inst.paidOn) : "—"}</td>
                <td className="right mono num" style={{ fontWeight: 500 }}>{fmtBRL2(inst.amount)}</td>
                <td>{statusPill(inst.status)}</td>
                <td>{boletoDocCell(inst)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.FinanceiroPage = FinanceiroPage;
