/* Disputes — list-detail: the list on the left, the dispute the route names on
   the right. /disputes/:id is that selection, not a second screen.
   Commit model: INSTANT. Submitting evidence opens a staged dialog from this
   instant screen; accepting a dispute is irreversible and opens a confirm
   dialog. A dispute under review offers nothing, and the panel says who the
   clock belongs to.
   Data state: populated. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Button, Badge, Separator, Alert, AlertTitle, AlertDescription,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription,
  } = window.OriginDesignSystem_7c998b;

  function DisputeRow({ dispute, active, now, onNavigate }) {
    const soon = DISPUTE_FLAGS.isOpen(dispute) && DISPUTE_FLAGS.isClosingSoon(dispute, now);
    return (
      <button type="button" className={"fd-pick" + (active ? " fd-pick--on" : "")} onClick={() => onNavigate("/disputes/" + dispute.id)}>
        <span className="fd-list__main">
          <span className="fd-record__name">{dispute.customer}</span>
          <span className="fd-record__meta"><code>{dispute.id}</code> · {dispute.reason}</span>
        </span>
        <span className="fd-list__side">
          <span className="fd-amount">{formatMoney(dispute.amount)}</span>
          <span className={"fd-clock" + (soon ? " fd-clock--danger" : "")}>
            {dispute.evidenceDueAt ? formatCountdown(dispute.evidenceDueAt, now) : "With the network"}
          </span>
        </span>
        <span className="fd-pick__foot"><StatusBadge values={DISPUTE_STATUS} value={dispute.status} /></span>
      </button>
    );
  }

  function DisputesScreen({ data, now, selectedId, onNavigate, onDisputeTransition, onPostComment }) {
    const disputes = data.disputes;
    const open = openDisputes(disputes);
    const needsEvidence = disputesNeedingEvidence(disputes);
    const dispute = selectedId ? disputes.find((d) => d.id === selectedId) : null;
    const payment = dispute ? data.payments.find((p) => p.id === dispute.paymentId) : null;
    const soon = dispute && DISPUTE_FLAGS.isOpen(dispute) && DISPUTE_FLAGS.isClosingSoon(dispute, now);

    return (
      <div className="fd-page">
        <PageHeader
          path={dispute ? "/disputes/:id" : "/disputes"}
          title={dispute ? dispute.customer : "Disputes"}
          actions={dispute ? <Transitions transitions={disputeTransitions(dispute)} onRun={(t) => onDisputeTransition(dispute, t)} size="default" /> : null}
        />

        <div className="fd-columns">
          <div className="fd-col">
            {dispute ? (
              <>
                {soon ? (
                  <Alert variant="error">
                    <AlertTitle>Evidence due — {formatCountdown(dispute.evidenceDueAt, now)}</AlertTitle>
                    <AlertDescription>After that the card network decides without us and {formatMoney(dispute.amount)} is lost. The money is already held back against the balance.</AlertDescription>
                  </Alert>
                ) : null}
                <Card>
                  <CardHeader>
                    <CardTitle>The claim</CardTitle>
                    <CardDescription>{dispute.reason} · opened {formatWhen(dispute.openedAt, now)}</CardDescription>
                  </CardHeader>
                  <CardPanel>
                    <dl className="fd-defs">
                      <div><dt>Status</dt><dd><StatusBadge values={DISPUTE_STATUS} value={dispute.status} /></dd></div>
                      <div><dt>Customer</dt><dd>{dispute.customer}</dd></div>
                      <div><dt>Payment it came from</dt><dd><code>{dispute.paymentId}</code>{payment ? " · " + labelOf(PAYMENT_METHODS, payment.method) : ""}</dd></div>
                      <div><dt>Opened</dt><dd title={formatAbsolute(dispute.openedAt)}>{formatWhen(dispute.openedAt, now)}</dd></div>
                      <div><dt>Evidence due</dt><dd title={dispute.evidenceDueAt ? formatAbsolute(dispute.evidenceDueAt) : undefined}>{dispute.evidenceDueAt ? formatCountdown(dispute.evidenceDueAt, now) : "Nothing owed by us"}</dd></div>
                      {dispute.evidenceSubmittedAt ? <div><dt>Evidence sent</dt><dd title={formatAbsolute(dispute.evidenceSubmittedAt)}>{formatWhen(dispute.evidenceSubmittedAt, now)}</dd></div> : null}
                      <div className="fd-defs__total"><dt>Disputed</dt><dd>{formatMoney(dispute.amount)}</dd></div>
                    </dl>
                  </CardPanel>
                  <CardFooter className="fd-card-footer">
                    <span className="fd-footnote">
                      {DISPUTE_FLAGS.needsEvidence(dispute)
                        ? "The clock is ours: nothing happens until we answer."
                        : dispute.status === "under_review"
                          ? "The clock is the network's. Evidence went in " + formatWhen(dispute.evidenceSubmittedAt, now) + "; they take up to 75 days."
                          : "Closed."}
                    </span>
                  </CardFooter>
                </Card>
                {payment ? (
                  <Card>
                    <CardHeader>
                      <CardTitle>The payment</CardTitle>
                      <CardDescription>The payment owns the amount; the dispute reads it.</CardDescription>
                    </CardHeader>
                    <CardPanel>
                      <dl className="fd-defs">
                        <div><dt>Payment</dt><dd><code>{payment.id}</code></dd></div>
                        <div><dt>Status</dt><dd><StatusBadge values={PAYMENT_STATUS} value={payment.status} /></dd></div>
                        <div><dt>Method</dt><dd>{labelOf(PAYMENT_METHODS, payment.method)}</dd></div>
                        <div><dt>Taken</dt><dd title={formatAbsolute(payment.createdAt)}>{formatWhen(payment.createdAt, now)}</dd></div>
                        <div className="fd-defs__total"><dt>Amount</dt><dd>{formatMoney(payment.amount)}</dd></div>
                      </dl>
                    </CardPanel>
                    <CardFooter className="fd-card-footer">
                      <Button variant="outline" size="sm" onClick={() => onNavigate("/payments")}>Open in payments</Button>
                    </CardFooter>
                  </Card>
                ) : null}
                <ThreadCard
                  record={{ type: "dispute", id: dispute.id }}
                  data={data}
                  signedInId={MERIDIAN_SIGNED_IN}
                  now={now}
                  onPost={onPostComment}
                  description={DISPUTE_FLAGS.needsEvidence(dispute)
                    ? "What we know before we answer the network. Mention somebody to put it in their queue."
                    : "Kept with the case. Mention somebody to put it in their queue."}
                />
              </>
            ) : (
              <Card>
                <CardPanel>
                  <Empty>
                    <EmptyHeader>
                      <EmptyMedia variant="icon"><Icon name="shield-alert" size={18} /></EmptyMedia>
                      <EmptyTitle>Pick a dispute</EmptyTitle>
                      <EmptyDescription>
                        {needsEvidence.length
                          ? needsEvidence.length + " of the " + open.length + " open disputes are waiting on evidence from us."
                          : "Nothing is waiting on evidence from us."}
                      </EmptyDescription>
                    </EmptyHeader>
                  </Empty>
                </CardPanel>
              </Card>
            )}
          </div>

          <div className="fd-col">
            <Card>
              <CardHeader>
                <CardTitle>All disputes</CardTitle>
                <CardDescription>{formatMoney(disputeExposure(disputes))} held back against the {open.length} still open.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="fd-picklist">
                  {disputes.map((d) => (
                    <DisputeRow key={d.id} dispute={d} active={dispute && d.id === dispute.id} now={now} onNavigate={onNavigate} />
                  ))}
                </div>
              </CardPanel>
              <CardFooter className="fd-card-footer">
                <span className="fd-footnote">{disputes.length} disputes · {needsEvidence.length} need evidence.</span>
              </CardFooter>
            </Card>
          </div>
        </div>
      </div>
    );
  }

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