/* Balances — where the money is, and what is already claiming it.
   Commit model: INSTANT. The only actions on this screen are navigation.
   Data state: populated.
   Nothing here stores a total: available is the one stored figure, committed is
   the payouts that have not landed and reserved is the open disputes, both
   summed from the arrays printed beneath them. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell, Button, Badge,
  } = window.OriginDesignSystem_7c998b;

  function Part({ label, amount, total, tone, note }) {
    return (
      <div className="fd-part">
        <div className="fd-spread">
          <span>{label}</span>
          <span className="fd-amount">{formatMoney(amount)}</span>
        </div>
        <span className={"fd-bar" + (tone ? " fd-bar--" + tone : "")} role="img" aria-label={label + ", " + formatMoney(amount)}>
          <span className="fd-bar__fill" style={{ width: (total > 0 ? (amount / total) * 100 : 0).toFixed(1) + "%" }} />
        </span>
        <span className="fd-footnote">{note}</span>
      </div>
    );
  }

  function BalancesScreen({ data, now, onNavigate }) {
    const breakdown = balanceBreakdown(data.balance, data.payouts, data.disputes);
    const committing = pendingPayouts(data.payouts);
    const reserving = openDisputes(data.disputes);
    /* One window for the movement chart, stated in words beside it. */
    const movement = movementByDay(data.payments, data.payouts, data.expenses, now, 30);

    return (
      <div className="fd-page">
        <PageHeader path="/balances" title="Balances" />

        <div className="fd-metrics">
          <MetricTile icon="wallet" label="Available" value={formatMoney(breakdown.available)} qualifier={"Settled and unclaimed, in " + data.balance.bank} />
          <MetricTile icon="arrow-up-right" label="Committed" value={formatMoney(breakdown.committed)} qualifier={committing.length + " payouts approved, in transit or waiting on us"} />
          <MetricTile icon="shield-alert" label="Reserved" value={formatMoney(breakdown.reserved)} qualifier={reserving.length + " open disputes, held until the network decides"} />
          <MetricTile icon="layers" label="On the platform" value={formatMoney(breakdown.total)} qualifier="Available plus everything already claiming it" />
        </div>

        <Card>
          <CardHeader>
            <CardTitle>What the balance is made of</CardTitle>
            <CardDescription>Three parts of {formatMoney(breakdown.total)}. Only the first is yours to move today.</CardDescription>
          </CardHeader>
          <CardPanel>
            <div className="fd-stack">
              <Part label="Available" amount={breakdown.available} total={breakdown.total} note="Pays out on the workspace's schedule, or on demand." />
              <Part label="Committed to payouts" amount={breakdown.committed} total={breakdown.total} tone="soft" note={committing.length + " payouts, the largest " + formatMoney(Math.max.apply(null, committing.map((p) => p.amount).concat([0]))) + "."} />
              <Part label="Reserved against disputes" amount={breakdown.reserved} total={breakdown.total} tone="warn" note={reserving.length + " disputes; the money returns to available if they are won."} />
            </div>
          </CardPanel>
          <CardFooter className="fd-card-footer">
            <span className="fd-footnote">Available is the only stored figure. Committed and reserved are summed from the two tables below.</span>
          </CardFooter>
        </Card>

        <Card className="fd-card">
          <CardHeader>
            <CardTitle>What moved the balance</CardTitle>
            <CardDescription>Last 30 days. In is payments that settled; out is payouts that landed in the bank plus card spend that settled — approvals and authorisations move nothing yet.</CardDescription>
          </CardHeader>
          <CardPanel>
            <DayChart
              buckets={movement}
              series={[{ key: "in", label: "Settled in", rows: [{ key: "payments", noun: "payment" }] }, { key: "out", label: "Paid and spent out", tone: "soft", rows: [{ key: "payouts", noun: "payout" }, { key: "expenses", noun: "expense" }] }]}
              format={formatMoney}
              label="Money in and out a day"
              note={formatMoney(sumBy(movement, "in")) + " in and " + formatMoney(sumBy(movement, "out")) + " out over the window."}
            />
          </CardPanel>
          <CardFooter className="fd-card-footer">
            <span className="fd-footnote">The three parts above are today's position; these bars are how it got there.</span>
            <Button variant="outline" size="sm" onClick={() => onNavigate("/reports")}>Open reports</Button>
          </CardFooter>
        </Card>

        <div className="fd-columns fd-columns--even">
          <div className="fd-col">
            <Card>
              <CardHeader>
                <CardTitle>Committing it</CardTitle>
                <CardDescription>{committing.length} payouts that have left the queue but not the account.</CardDescription>
              </CardHeader>
              <div className="fd-card-table">
                <Table variant="card">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Destination</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="fd-num">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {committing.map((payout) => (
                      <TableRow key={payout.id}>
                        <TableCell>
                          <span className="fd-record">
                            <span className="fd-record__name">{payout.destination}</span>
                            <span className="fd-record__meta"><code>{payout.id}</code></span>
                          </span>
                        </TableCell>
                        <TableCell><StatusBadge values={PAYOUT_STATUS} value={payout.status} /></TableCell>
                        <TableCell className="fd-num fd-amount">{formatMoney(payout.amount)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              <CardFooter className="fd-card-footer">
                <span className="fd-footnote">Sums to {formatMoney(breakdown.committed)}.</span>
                <Button variant="outline" size="sm" onClick={() => onNavigate("/payouts")}>Open payouts</Button>
              </CardFooter>
            </Card>
          </div>

          <div className="fd-col">
            <Card>
              <CardHeader>
                <CardTitle>Reserving it</CardTitle>
                <CardDescription>{reserving.length} open disputes, held until each is decided.</CardDescription>
              </CardHeader>
              <div className="fd-card-table">
                <Table variant="card">
                  <TableHeader>
                    <TableRow>
                      <TableHead>Customer</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="fd-num">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {reserving.map((dispute) => (
                      <TableRow key={dispute.id}>
                        <TableCell>
                          <span className="fd-record">
                            <button type="button" className="fd-link fd-record__name" onClick={() => onNavigate("/disputes/" + dispute.id)}>{dispute.customer}</button>
                            <span className="fd-record__meta"><code>{dispute.id}</code> · {dispute.reason}</span>
                          </span>
                        </TableCell>
                        <TableCell><StatusBadge values={DISPUTE_STATUS} value={dispute.status} /></TableCell>
                        <TableCell className="fd-num fd-amount">{formatMoney(dispute.amount)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              <CardFooter className="fd-card-footer">
                <span className="fd-footnote">Sums to {formatMoney(breakdown.reserved)}.</span>
                <Button variant="outline" size="sm" onClick={() => onNavigate("/disputes")}>Open disputes</Button>
              </CardFooter>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { BalancesScreen });
})();
