/* Kay Construction — Laporan (Reports): monthly cash flow, profit per project, VAT recap, supplier recap, spend by category, retention. */

function ReportCard({ title, sub, children, right }) {
  return (
    <div className="card">
      <div className="card-head">
        <div><h2 className="section" style={{ margin: 0 }}>{title}</h2>{sub && <div className="tiny muted" style={{ marginTop: 3 }}>{sub}</div>}</div>
        {right}
      </div>
      <div className="card-body" style={{ paddingTop: 10 }}>{children}</div>
    </div>
  );
}

function ReportsPage() {
  useStore();
  const [lang] = useLang();
  const cash = S.cashFlowByMonth();
  const profit = S.profitByProject().filter((r) => r.contract > 0 || r.realisasi > 0);
  const ppn = S.ppnRecapByMonth();
  const suppliers = S.supplierRecap();
  const catMap = S.expensesByCategory();
  const cats = Object.keys(catMap).sort((a, b) => catMap[b] - catMap[a]);
  const catTotal = cats.reduce((s, c) => s + catMap[c], 0);
  const retOut = S.retentionOutstanding();

  const cashIn = cash.reduce((s, r) => s + r.in, 0);
  const cashOut = cash.reduce((s, r) => s + r.out, 0);

  return (
    <div>
      <PageHead title={t("rep.title")} sub={t("rep.sub")} />

      <div className="kpi-grid">
        <KPICard label={t("rep.cashIn")} value={S.formatRupiah(cashIn)} small icon="kwitansi" accent="pos"
          meta={cash.length + " " + t("rep.month").toLowerCase()} />
        <KPICard label={t("rep.cashOut")} value={S.formatRupiah(cashOut)} small icon="expenses"
          meta={t("exp.title")} />
        <KPICard label={t("rep.net")} value={S.formatRupiah(cashIn - cashOut)} small icon="dashboard"
          accent={cashIn - cashOut < 0 ? "neg" : null} />
        <KPICard label={t("ret.pending")} value={S.formatRupiah(retOut)} small icon="clock"
          accent={retOut > 0 ? "neg" : null} meta={t("ret.title")} />
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
        <ReportCard title={t("rep.cash")} sub={t("rep.cashIn") + " vs " + t("rep.cashOut")}>
          {cash.length === 0 ? <div className="muted tiny">{t("common.empty")}</div> : (
            <div className="table-wrap"><table className="tbl">
              <thead><tr><th>{t("rep.month")}</th><th className="num">{t("rep.cashIn")}</th><th className="num">{t("rep.cashOut")}</th><th className="num">{t("rep.net")}</th></tr></thead>
              <tbody>
                {cash.map((r) => (
                  <tr key={r.month}>
                    <td data-label={t("rep.month")} style={{ fontWeight: 500 }}>{S.formatMonth(r.month, lang)}</td>
                    <td data-label={t("rep.cashIn")} className="num" style={{ color: "var(--pos)" }}>{S.formatRupiah(r.in)}</td>
                    <td data-label={t("rep.cashOut")} className="num">{S.formatRupiah(r.out)}</td>
                    <td data-label={t("rep.net")} className="num" style={{ fontWeight: 600, color: r.net < 0 ? "var(--neg)" : "inherit" }}>{S.formatRupiah(r.net)}</td>
                  </tr>
                ))}
              </tbody>
            </table></div>
          )}
        </ReportCard>

        <div className="grid-2" style={{ alignItems: "start" }}>
          <ReportCard title={t("rep.profit")} sub={lang === "en" ? "Contract − actual cost" : "Kontrak − realisasi"}>
            {profit.length === 0 ? <div className="muted tiny">{t("common.empty")}</div> : (
              <div className="table-wrap"><table className="tbl">
                <thead><tr><th>{t("common.project")}</th><th className="num">{t("col.contract")}</th><th className="num">{t("col.actual")}</th><th className="num">{t("dash.kpi.margin")}</th></tr></thead>
                <tbody>
                  {profit.map((r) => (
                    <tr key={r.project.id} className="clickable" onClick={() => go("#/proyek/" + r.project.id)}>
                      <td data-label={t("common.project")}><div style={{ fontWeight: 500 }}>{r.project.name}</div><div className="subtle"><StatusBadge status={r.status} /></div></td>
                      <td data-label={t("col.contract")} className="num">{S.formatRupiah(r.contract)}</td>
                      <td data-label={t("col.actual")} className="num">{S.formatRupiah(r.realisasi)}</td>
                      <td data-label={t("dash.kpi.margin")} className="num" style={{ fontWeight: 600, color: r.margin < 0 ? "var(--neg)" : "var(--pos)" }}>{S.formatRupiah(r.margin)}</td>
                    </tr>
                  ))}
                </tbody>
              </table></div>
            )}
          </ReportCard>

          <ReportCard title={t("rep.ppn")} sub={lang === "en" ? "Output VAT from issued invoices" : "PPN keluaran dari invoice terbit"}>
            {ppn.length === 0 ? <div className="muted tiny">{t("common.empty")}</div> : (
              <div className="table-wrap"><table className="tbl">
                <thead><tr><th>{t("rep.month")}</th><th className="num">{t("rep.dpp")}</th><th className="num">{t("common.ppn")}</th></tr></thead>
                <tbody>
                  {ppn.map((r) => (
                    <tr key={r.month}>
                      <td data-label={t("rep.month")} style={{ fontWeight: 500 }}>{S.formatMonth(r.month, lang)}</td>
                      <td data-label={t("rep.dpp")} className="num">{S.formatRupiah(r.dpp)}</td>
                      <td data-label={t("common.ppn")} className="num" style={{ fontWeight: 600 }}>{S.formatRupiah(r.ppn)}</td>
                    </tr>
                  ))}
                </tbody>
              </table></div>
            )}
          </ReportCard>
        </div>

        <div className="grid-2" style={{ alignItems: "start" }}>
          <ReportCard title={t("rep.supplier")} sub={lang === "en" ? "Total spend per supplier" : "Total belanja per supplier"}>
            {suppliers.length === 0 ? <div className="muted tiny">{t("common.empty")}</div> : (
              <div className="table-wrap"><table className="tbl">
                <thead><tr><th>{t("exp.supplier")}</th><th className="num">{t("rep.txns")}</th><th className="num">{t("common.total")}</th></tr></thead>
                <tbody>
                  {suppliers.map((r) => (
                    <tr key={r.supplier}>
                      <td data-label={t("exp.supplier")} style={{ fontWeight: 500 }}>{r.supplier}</td>
                      <td data-label={t("rep.txns")} className="num subtle">{r.count}</td>
                      <td data-label={t("common.total")} className="num" style={{ fontWeight: 600 }}>{S.formatRupiah(r.total)}</td>
                    </tr>
                  ))}
                </tbody>
              </table></div>
            )}
          </ReportCard>

          <ReportCard title={t("rep.byCategory")} sub={t("exp.title")}>
            {cats.length === 0 ? <div className="muted tiny">{t("common.empty")}</div> : (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {cats.map((c) => {
                  const pct = catTotal > 0 ? (catMap[c] / catTotal) * 100 : 0;
                  return (
                    <div key={c}>
                      <div className="between" style={{ marginBottom: 5 }}>
                        <span style={{ fontWeight: 600, fontSize: 13 }}>{t("exp.cat." + c) === "exp.cat." + c ? c : t("exp.cat." + c)}</span>
                        <span className="tnum tiny">{S.formatRupiah(catMap[c])} · {Math.round(pct)}%</span>
                      </div>
                      <div className="meter"><span style={{ width: pct + "%" }}></span></div>
                    </div>
                  );
                })}
              </div>
            )}
          </ReportCard>
        </div>

        <ReportCard title={t("ret.title")} sub={t("ret.sub")}>
          {window.RetentionList ? <RetentionList /> : null}
        </ReportCard>
      </div>
    </div>
  );
}

Object.assign(window, { ReportsPage });
