/* ==================================================================
   Operations → Finance
   ------------------------------------------------------------------
   The school's finance system (the Ledger app) surfaced in the admin
   panel. It is a SEPARATE Postgres database on
   port 5432, read through a read-only pool — see backend db/ledger.ts.

   Because it is a separate deployment it may simply not be running. That
   is an ordinary state, not an error: the whole screen becomes one
   "not connected" card that says which knob to turn, and no tile ever
   prints a zero that could be mistaken for "collected nothing".

   READ-ONLY BY DESIGN. Nothing here writes to the finance system; the
   book of record stays in the Ledger's own app.
   ================================================================== */

const FinanceScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state = CX.useCockpitData("/admin/cockpit/finance", { pollMs: 300000 });
  const d = state.data;

  const COMPONENT_COLOR = {
    TUITION: "var(--green-solid)", TRANSPORT: "var(--blue-solid)",
    HOSTEL: "var(--pink-solid)", READMISSION: "var(--amber-solid)",
    SECURITY: "var(--violet-solid)",
  };

  const exportCsv = () => {
    if (!d?.connected) return;
    CX.exportCsv("fee-collection-by-month.csv", [
      ["Month", "Receipts", "Amount (INR)"],
      ...d.collection.byMonth.map((m) => [m.month, m.n, m.amount]),
    ]);
  };

  const FiBadge = window.AppUI.StatusBadge;
  const FiRow = window.AppUI.ListRow;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Ledger · finance system"
        title="Finance"
        status={d && (d.connected
          ? <FiBadge tone="green" variant="outline">Connected</FiBadge>
          : <FiBadge tone="amber" variant="outline">Not connected</FiBadge>)}
        actions={d?.connected && (
          <button type="button" className="btn primary" onClick={exportCsv}>
            <CX.Icon name="download" size={15}/> Export collection
          </button>
        )}
      />

      <CX.Screen state={state} skeleton={<CX.Skeleton rows={3} height={190}/>}>
        {d && !d.connected && (
          <CX.NotConnected
            title="Finance system not connected"
            what="The Ledger database isn't reachable from this backend, so fee, payroll and asset figures can't be read."
            why="It is a separate Postgres — locally on port 5432. Start it, or point the backend at it with LEDGER_PGHOST / LEDGER_PGPORT / LEDGER_PGDATABASE."
          />
        )}

        {d?.connected && (
          <>
            {/* ---- Headline tiles ---- */}
            <div className="cx-grid cols-3" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
              <CX.StatCard
                icon="rupee" color="var(--green-solid)" label="Collected this month"
                value={CX.money(d.collection.thisMonth)}
                delta={d.collection.deltaPct != null
                  ? `${d.collection.deltaPct >= 0 ? "↑" : "↓"} ${Math.abs(d.collection.deltaPct)}%`
                  : null}
                deltaTone={d.collection.deltaPct >= 0 ? "up" : "down"}
                footNote={`${CX.money(d.collection.lastMonth)} last month · ${CX.money(d.collection.today)} today`}
                action={<CX.Tag>Live</CX.Tag>}
              />
              <CX.StatCard
                icon="wallet" color="var(--blue-solid)" label="Collected all time"
                value={CX.money(d.collection.allTime)}
                delta={`${CX.num(d.collection.payments)} receipts`}
                deltaTone="flat"
                footNote={d.collection.since ? `since ${CX.date(d.collection.since, { day: "numeric", month: "short", year: "numeric" })}` : ""}
                action={<CX.Tag>{d.students.active} active students</CX.Tag>}
              />
              <CX.StatCard
                icon="box" color="var(--pink-solid)" label="Assets on register"
                value={CX.num(d.assets.total)}
                delta={CX.money(d.assets.value)}
                deltaTone="flat"
                footNote={`${d.assets.inUse} in use · ${d.assets.inStock} in stock`}
                action={<CX.Tag>Register</CX.Tag>}
              />
            </div>

            {/* ---- Trend · mix ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1.3fr 1fr", marginBottom: 20 }}>
              <CX.Card>
                <CX.CardHead
                  title="Collection trend"
                  sub={`${CX.num(d.collection.byMonth.reduce((a, m) => a + m.n, 0))} receipts in the window`}
                  right={<CX.Tag>Last 8 months</CX.Tag>}
                />
                <div className="cx-stat-value" style={{ marginBottom: 18 }}>
                  {CX.money(d.collection.byMonth.reduce((a, m) => a + m.amount, 0))}
                </div>
                <div style={{ display: "flex", alignItems: "flex-end", gap: 10, height: 170 }}>
                  {d.collection.byMonth.map((m) => (
                    <div key={m.month} style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", height: "100%", minWidth: 0 }}
                         title={`${m.month}: ${CX.money(m.amount, { full: true })} across ${m.n} receipts`}>
                      <div style={{
                        height: `${Math.max(6, m.heightPct)}%`,
                        background: "var(--green-solid)", borderRadius: "var(--radius-ctl)",
                        opacity: 0.35 + 0.65 * (m.heightPct / 100),
                      }}/>
                    </div>
                  ))}
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
                  {d.collection.byMonth.map((m) => (
                    <div key={m.month} style={{
                      flex: 1, textAlign: "center", fontSize: 11, fontWeight: 500, letterSpacing: "0.06em",
                      color: "var(--ink-3)", minWidth: 0, overflow: "hidden",
                    }}>
                      {new Date(m.month + "-01T00:00:00").toLocaleDateString("en-IN", { month: "short" }).toUpperCase()}
                    </div>
                  ))}
                </div>
                <CX.CardFoot note="Read-only view of the Ledger · the finance app remains the book of record"/>
              </CX.Card>

              <CX.Card>
                <CX.CardHead title="Collection mix" right={<CX.Tag>By head</CX.Tag>}/>
                <div style={{ display: "flex", flexDirection: "column", gap: 14, marginBottom: 20 }}>
                  {d.collection.byComponent.map((c) => {
                    const share = d.collection.allTime
                      ? Math.round((c.amount / d.collection.allTime) * 100) : 0;
                    return (
                      <div key={c.component || "other"}>
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, marginBottom: 7, gap: 12 }}>
                          <span style={{ fontWeight: 500, color: "var(--ink-0)" }}>
                            {CX.title(c.component || "Other")}
                          </span>
                          <span style={{ color: "var(--ink-3)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }}>
                            <strong style={{ color: "var(--ink-0)", fontWeight: 600 }}>{CX.money(c.amount)}</strong> · {c.n}
                          </span>
                        </div>
                        <CX.Meter pct={share} color={COMPONENT_COLOR[c.component] || "var(--grey-solid)"}/>
                      </div>
                    );
                  })}
                </div>
                <div className="ui-section-label" style={{ marginBottom: 10, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                  Payment mode
                </div>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {d.collection.byMode.map((m) => (
                    <FiBadge key={m.mode} tone="grey">
                      {CX.title(m.mode || "Other")} · {CX.num(m.n)}
                    </FiBadge>
                  ))}
                </div>
              </CX.Card>
            </div>

            {/* ---- Entities · payables · payroll ---- */}
            <div className="cx-grid split" style={{ gridTemplateColumns: "1.2fr 1fr" }}>
              <CX.Card>
                <CX.CardHead title="By institution" right={<CX.Tag>{d.entities.length} entities</CX.Tag>}/>
                <div className="ui-list">
                  {d.entities.length === 0 ? (
                    <CX.Empty icon="building" title="No entities configured"/>
                  ) : d.entities.map((e) => (
                    <FiRow key={e.name}
                      leading={
                        <div className="cx-av" style={{
                          background: e.color ? `color-mix(in srgb, ${e.color} 16%, transparent)` : "var(--bg-3)",
                          color: e.color || "var(--ink-2)", fontSize: 11, fontWeight: 600,
                        }}>{(e.shortName || e.name || "?").slice(0, 3).toUpperCase()}</div>
                      }
                      title={e.name}
                      sub={`${CX.num(e.students)} active student(s)`}
                      amount={CX.money(e.collected)}
                    />
                  ))}
                </div>
                <CX.CardFoot
                  note={`${CX.num(d.students.withUid)} of ${CX.num(d.students.total)} Ledger students carry a portal UID`}
                />
              </CX.Card>

              <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
                <CX.Card>
                  <CX.CardHead
                    title="Payables & payroll"
                    right={d.payables.unpaid > 0
                      ? <FiBadge tone="amber">{d.payables.unpaid} unpaid</FiBadge>
                      : <FiBadge tone="green">Settled</FiBadge>}
                  />
                  <window.AppUI.StatRow flush align="left" items={[
                    { value: CX.money(d.payables.unpaidAmount), label: "Unpaid vendor bills", tone: d.payables.unpaid > 0 ? "amber" : undefined },
                    { value: CX.money(d.payroll.amount), label: "Salary paid this year" },
                  ]}/>
                  <div className="cx-card-foot" style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    {d.payables.bills} bill(s) on record · {d.payroll.payments} salary payment(s) ·{" "}
                    {d.payroll.employees} active employee(s)
                  </div>
                </CX.Card>

                <CX.Card>
                  <CX.CardHead title="Account balances" right={<CX.Tag>{d.accounts.length} accounts</CX.Tag>}/>
                  {d.accounts.length === 0 ? (
                    <CX.Empty icon="wallet" title="No accounts configured"/>
                  ) : (
                    // Capped rather than scrolled: a scroll container inside a
                    // card clips its last row mid-height and reads as broken.
                    <div className="ui-list">
                      {d.accounts.slice(0, 6).map((a, i) => (
                        <FiRow key={i}
                          leading={<FiBadge tone="grey">{a.type}</FiBadge>}
                          title={a.name}
                          amount={
                            <span style={{ color: a.balance < 0 ? "var(--red)" : undefined }}>{CX.money(a.balance)}</span>
                          }
                        />
                      ))}
                      {d.accounts.length > 6 && (
                        <div style={{ fontSize: 13, color: "var(--ink-3)", paddingTop: 12 }}>
                          +{d.accounts.length - 6} more account(s) in the Ledger
                        </div>
                      )}
                    </div>
                  )}
                </CX.Card>
              </div>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitFinance = FinanceScreen;
