Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

90.0 KB
Raw Blame
// Server admin › Billing (PR 13): the bills of this install with their ledger, payments and
// invoices; what waits for review; the Stripe event inbox; the install's billing rules; and the billing switch (Stripe's
// keys are connected under Providers, self-serve sign-up is set under Settings › Sign-up: LIN-693). Every write asks why (kept in the audit log) and runs through runAdmin, so the server's passkey step-up asks
// for the admin's passkey first; the ones that reach Stripe send one request id per dialog (its idempotency key).
//
// The page: one card of rows, as on Server admin › Overview (UI cleanup E, A2): bills, review, Stripe events, sign-up,
// prices and rules, Stripe, each with its state and a link to its own page (`#admin/billing/<tab>`, route.ts). A part
// opens like a workspace from its list, with a crumb back, so only the part on screen loads its rows. The rows are one
// read (billing.adminSummary), kept between visits.
import type {
  AdminBillCustomer,
  AdminBillDetail,
  AdminBillingSummary,
  AdminBillRow,
  AdminBillStatus,
  AdminReviewRow,
  AdminStripeEvent,
  BillingEventFilter,
  BillingRulesData,
  RadarRiskLevel,
  SelfServeData,
  TaxAddressMissingData,
} from '@linedesk/actions'
import { PLAN_PRICE_FLOOR, RADAR_RISK_LEVELS } from '@linedesk/actions'
import { SIGNUP_RULE_RANGES, type SignupCountRule } from '@linedesk/db/types'
import { type MessageKey, msg } from '@linedesk/i18n'
import { T, useT } from '@linedesk/i18n/react'
import { type FormEvent, Fragment, type ReactNode, useContext, useEffect, useMemo, useState } from 'react'
import { refreshQuery, setQueryData, useQuery } from '../cachedQuery.ts'
import { fmt } from '../i18n/format.ts'
import { i18n } from '../i18n/index.tsx'
import { AppLink, appLink, LinkButton } from '../ui/AppLink.tsx'
import { Checkbox, Select, Switch } from '../ui/controls.tsx'
import { LineGroup, LinkLine } from '../ui/FeatureLine.tsx'
import { FilterChip, FilterChips } from '../ui/FilterChips.tsx'
import {
  Card,
  CardInline,
  Dialog,
  FormField,
  FormMessage,
  HelpTip,
  Input,
  onSaveKey,
  SaveBar,
  Textarea,
} from '../ui/form.tsx'
import { Badge, Button, cx, Note } from '../ui/kit.tsx'
import { Loading, Skeleton, SkeletonRows, SkeletonText } from '../ui/LoadStates.tsx'
import { ListEmpty } from '../ui/list.tsx'
import { SettingRow, SkeletonSettingRow } from '../ui/SettingRow.tsx'
import { AdminList, type Column, ListCard, type ListKeys, ListTable } from './AdminList.tsx'
import { type AdminAction, DetailActions, RowActions, useActionRunner } from './actions.tsx'
import type { AdminData } from './api.ts'
import { runAdmin } from './api.ts'
import { BillingSwitch } from './BillingSwitch.tsx'
import {
  ago,
  BILL_FILTERS,
  type BillFilter,
  billFilterOfHash,
  billsHref,
  blankIsNone,
  changedFields,
  defaultText,
  eventFilterOfHash,
  eventsHref,
  exactTime,
  type FieldUnit,
  filterBills,
  hubGroups,
  newRequestId,
  parseCount,
  parseDollars,
  RULE_GROUPS,
  type RuleField,
  type RuleGroupId,
  type RulesForm,
  rateOfMicros,
  reasonProblem,
  rulesFloorText,
  rulesForm,
  rulesFromForm,
  ruleUnit,
  SIGNUP_GROUPS,
  type SignupForm,
  sameText,
  signupChanges,
  signupDirty,
  signupForm,
  signupFromForm,
  usdOfCents,
  usdOfMicros,
  usdSymbol,
} from './billingModel.ts'
import { CALL_QUALITY, loadCallQuality } from './CallQuality.tsx'
import { errorText, type Notify } from './notify.ts'
import { day, EMPTY, when } from './parts.tsx'
import { type BillingTab, billingTab } from './route.ts'
import { Fact } from './WorkspacesPage.tsx'

type Translate = ReturnType<typeof useT>

const BILLS = 'admin.billing.bills'
const REVIEW = 'admin.billing.review'
const RULES = 'admin.billing.rules'
const SUMMARY = 'admin.billing.summary'
export const SELF_SERVE = 'admin.billing.selfServe'
const billKey = (id: string) => `admin.billing.bill.${id}`
const eventsKey = (filter: BillingEventFilter) => `admin.billing.events.${filter}`

const loadBills = async () => ((await runAdmin('billing.adminBills', {})) as { bills: AdminBillRow[] }).bills
const loadBill = (id: string) => async () =>
  (await runAdmin('billing.adminBill', { billingAccountId: id })) as unknown as AdminBillDetail
const customerKey = (id: string) => `admin.billing.customer.${id}`
const loadCustomer = (id: string) => async () =>
  ((await runAdmin('billing.adminCustomer', { billingAccountId: id })) as unknown as AdminBillCustomer).customer
const loadReview = async () =>
  (await runAdmin('billing.adminReview', {})) as unknown as { held: AdminReviewRow[]; newTrials: AdminReviewRow[] }
const loadSummary = async () => (await runAdmin('billing.adminSummary', {})) as unknown as AdminBillingSummary
const loadRules = async () => (await runAdmin('billingRules.get', {})) as unknown as BillingRulesData
const loadTaxAddress = async () =>
  ((await runAdmin('billing.adminTaxAddressMissing', {})) as unknown as TaxAddressMissingData).taxAddressMissing
export const loadSelfServe = async () => (await runAdmin('signup.getSelfServe', {})) as unknown as SelfServeData
type EventsPage = { events: AdminStripeEvent[]; next: string | null }
const loadEvents = (filter: BillingEventFilter, before?: string) => async () =>
  (await runAdmin('billing.adminEvents', { filter, ...(before ? { before } : {}) })) as unknown as EventsPage

/**
 * The status line, the rules and the sign-up settings hold no customer's data: kept in this browser between visits
 * (per member, forgotten on sign-out), so the page shows them at once and reads them again in the background. Bills
 * and events, which name customers, stay in memory only.
 */
export const KEPT = { persist: true } as const

/** After a write: the bill, the list, the review and the status line read again, so the page shows what was just done. */
async function refreshBill(id: string) {
  await Promise.all([refreshQuery(billKey(id)), refreshQuery(BILLS), refreshQuery(REVIEW), refreshQuery(SUMMARY)])
}

const STATUS: Record<AdminBillStatus, MessageKey> = {
  pending_payment: msg('admin.bills.status.pendingPayment'),
  trialing: msg('admin.bills.status.trialing'),
  active: msg('admin.bills.status.active'),
  past_due: msg('admin.bills.status.pastDue'),
  suspended: msg('admin.bills.status.suspended'),
  canceled: msg('admin.bills.status.canceled'),
  comped: msg('admin.bills.status.comped'),
}

/** A bill's status as a badge: red where money is owed or calls are stopped, ink when it pays, blue-grey in the trial. */
const STATUS_TONE: Record<AdminBillStatus, 'neutral' | 'ok' | 'danger' | 'info' | 'outline'> = {
  pending_payment: 'outline',
  trialing: 'info',
  active: 'ok',
  past_due: 'danger',
  suspended: 'danger',
  canceled: 'neutral',
  comped: 'neutral',
}

function StatusBadge({ status }: { status: AdminBillStatus }) {
  const t = useT()
  return <Badge tone={STATUS_TONE[status]}>{t(STATUS[status])}</Badge>
}

const RISK: Record<RadarRiskLevel, MessageKey> = {
  normal: msg('admin.bills.risk.normal'),
  elevated: msg('admin.bills.risk.elevated'),
  highest: msg('admin.bills.risk.highest'),
  not_assessed: msg('admin.bills.risk.notAssessed'),
  unknown: msg('admin.bills.risk.unknown'),
}

/** Stripe Radar's risk level of the trial's card check; a level Radar adds later shows as it comes. */
function RiskBadge({ level }: { level: string | null }) {
  const t = useT()
  if (!level) return <span className="adm-muted">{t('admin.bills.risk.none')}</span>
  const key = RISK[level as RadarRiskLevel]
  const tone = level === 'highest' ? 'danger' : level === 'elevated' ? 'outline' : 'neutral'
  return <Badge tone={tone}>{key ? t(key) : level}</Badge>
}

/** A moment as "3 hours ago", the exact time on hover and for screen readers' `dateTime`. */
function Ago({ iso }: { iso: string }) {
  return (
    <time dateTime={iso} title={exactTime(iso)}>
      {ago(iso)}
    </time>
  )
}

const ownerText = (t: Translate, owner: { email: string | null; name: string | null }) =>
  owner.email ?? owner.name ?? t('admin.bills.noOwner')

/**
 * The title of `#admin/billing/<id>`: a part's name, or whose bill it is, from the bill or the list, whichever is here
 * first; null on Billing's own page.
 */
export function useBillTitle(id: string | null): string | null {
  const t = useT()
  const billId = billingTab(id) === null ? id : null
  const bill = useQuery(billId ? billKey(billId) : null, loadBill(billId ?? '')).data
  const bills = useQuery(billId ? BILLS : null, loadBills).data
  if (!billId) return billingPartTitle(t, id)
  const owner = bill?.owner ?? bills?.find(b => b.id === billId)?.owner
  return owner ? t('admin.bills.detail.title', { owner: ownerText(t, owner) }) : t('admin.bills.detail.untitled')
}

type Props = {
  /** A section of the page (route.ts `BILLING_TABS`) or a bill's id. */
  id: string | null
  onOpen: (id: string) => void
  notify: Notify
  keysRef: { current: ListKeys | null }
  /** The admin data (null until it is read): the billing switch reads Stripe's keys from it. */
  data: AdminData | null
  /** The page header's actions slot: a bill puts its actions there. */
  headActions?: HTMLElement | null
}

export function Billing({ id, onOpen, notify, keysRef, data, headActions }: Props) {
  const tab = billingTab(id)
  if (!tab) return <BillDetail id={id!} notify={notify} slot={headActions ?? null} />
  switch (tab) {
    case 'overview':
      return <BillingHome data={data} notify={notify} />
    case 'bills':
      return <BillsList onOpen={onOpen} keysRef={keysRef} />
    case 'review':
      return <ReviewCard onOpen={onOpen} notify={notify} />
    case 'events':
      return <EventsCard notify={notify} />
    case 'rules':
      return <RulesCard notify={notify} />
  }
}

const TAB_LABELS: Record<BillingTab, MessageKey> = {
  overview: msg('admin.bills.tab.overview'),
  bills: msg('admin.bills.tab.bills'),
  review: msg('admin.bills.tab.review'),
  events: msg('admin.bills.tab.events'),
  rules: msg('admin.bills.tab.rules'),
}

/** The title of a part of Billing (`#admin/billing/<tab>`); null on Billing's own page and for a bill. */
export function billingPartTitle(t: Translate, id: string | null): string | null {
  const tab = billingTab(id)
  return tab && tab !== 'overview' ? t(TAB_LABELS[tab]) : null
}

/**
 * The line under a part's title and its help (Review, Stripe events, Prices and rules): shown in the page header, so the
 * page does not repeat the title and the (?) sits after it. Null for the other parts and for a bill.
 */
export function billingPartIntro(t: Translate, id: string | null): { description: string; help: string } | null {
  const tab = billingTab(id)
  if (tab === 'review')
    return { description: t('admin.bills.review.description'), help: t('admin.bills.review.radarHelp') }
  if (tab === 'events')
    return { description: t('admin.bills.events.descriptionShort'), help: t('admin.bills.events.description') }
  if (tab === 'rules') return { description: t('admin.bills.rules.intro'), help: t('admin.bills.rules.description') }
  return null
}

// ---- Billing's own page: a line per part, under Money and Setup ----

/** Billing at a glance (also the Overview's Needs you, NeedsYou.tsx). */
export const useSummary = () => useQuery(SUMMARY, loadSummary, KEPT)

/**
 * Billing's own page: its parts as lines like Features', each opening the part's own page; under Setup the two
 * switches (billing through Stripe, Stripe Tax) are lines of their own (Billing › Stripe was a page of only them).
 */
function BillingHome({ data: admin, notify }: { data: AdminData | null; notify: Notify }) {
  const t = useT()
  const query = useSummary()
  const data = query.data
  return (
    <Loading
      what={t('admin.bills.summary.label')}
      loading={!data}
      error={query.error}
      onRetry={() => void query.reload()}
      skeleton={<HubSkeleton />}
      className="adm-billhome"
    >
      {data &&
        hubGroups(data).map(group => (
          <Fragment key={group.id}>
            <LineGroup>{group.label}</LineGroup>
            {group.id === 'setup' && (
              <>
                <section className="k-card k-feature" aria-label={t('admin.billing.switch')}>
                  {admin ? <BillingSwitch data={admin} /> : <SkeletonSettingRow control="switch" />}
                </section>
                <TaxLine notify={notify} />
              </>
            )}
            {group.lines.map(({ id, action, ...line }) => (
              <LinkLine key={id} {...line} label={action} />
            ))}
          </Fragment>
        ))}
    </Loading>
  )
}

/** The page while the summary loads: the groups' headings at once, their lines in their shape. */
function HubSkeleton() {
  const t = useT()
  const groups: [string, ('button' | 'switch')[]][] = [
    [t('admin.bills.hub.operations'), ['button', 'button', 'button']],
    [t('admin.bills.hub.setup'), ['switch', 'switch', 'button']],
  ]
  return groups.map(([label, controls]) => (
    <Fragment key={label}>
      <LineGroup>{label}</LineGroup>
      {controls.map((control, line) => (
        // biome-ignore lint/suspicious/noArrayIndexKey: placeholder lines never reorder
        <section key={line} className="k-card k-feature">
          <SkeletonSettingRow index={line} control={control} />
        </section>
      ))}
    </Fragment>
  ))
}

/**
 * Server admin › Sign-up & access (was Billing › Sign-up): self-serve sign-up, who may sign up and from where, its
 * limits, the emails new workspaces get, and the names no partner brand may use.
 */
// ---- Bills ----

const billColumns = (t: Translate): Column<AdminBillRow>[] => [
  {
    key: 'owner',
    label: t('admin.bills.column.owner'),
    sort: b => ownerText(t, b.owner),
    render: b => (
      <span className="adm-strong">
        {ownerText(t, b.owner)}
        {b.kind === 'partner' && <Badge>{t('admin.bills.kind.partner')}</Badge>}
        {b.heldForReviewAt && <Badge tone="danger">{t('admin.bills.badge.held')}</Badge>}
        <span className="adm-sub">
          {b.workspaces.length
            ? fmt().list(
                b.workspaces.map(w => w.name),
                { type: 'unit', style: 'short' },
              )
            : t('admin.bills.noWorkspaces')}
        </span>
      </span>
    ),
  },
  {
    key: 'status',
    label: t('admin.bills.column.status'),
    sort: b => b.status,
    render: b => <StatusBadge status={b.status} />,
  },
  {
    key: 'balance',
    label: t('admin.bills.column.balance'),
    numeric: true,
    firstDir: 'asc',
    sort: b => b.balanceMicros,
    render: b => usdOfMicros(b.balanceMicros),
  },
  {
    key: 'created',
    label: t('admin.bills.column.created'),
    firstDir: 'desc',
    wide: true,
    sort: b => Date.parse(b.createdAt),
    render: b => <Ago iso={b.createdAt} />,
  },
]

const filterLabel = (t: Translate, value: BillFilter) =>
  value === 'current'
    ? t('admin.bills.filter.current')
    : value === 'all'
      ? t('admin.bills.filter.all')
      : value === 'held'
        ? t('admin.bills.filter.held')
        : t(STATUS[value])

/** The filter a link asked for (`#admin/billing/bills?status=…`), followed when the address changes. */
function useHashFilter<F extends string>(parse: (hash: string) => F, href: (filter: F) => string) {
  const [filter, setFilter] = useState(() => parse(typeof window === 'undefined' ? '' : window.location.hash))
  useEffect(() => {
    const onHash = () => setFilter(parse(window.location.hash))
    window.addEventListener('hashchange', onHash)
    return () => window.removeEventListener('hashchange', onHash)
  }, [parse])
  /** A new filter replaces the address (no history entry per click), so a reload or a shared link keeps it. */
  const choose = (next: F) => {
    setFilter(next)
    window.history.replaceState(window.history.state, '', href(next))
  }
  return [filter, choose] as const
}

function BillsList({ onOpen, keysRef }: { onOpen: (id: string) => void; keysRef: { current: ListKeys | null } }) {
  const t = useT()
  const query = useQuery(BILLS, loadBills)
  const columns = useMemo(() => billColumns(t), [t])
  const [filter, setFilter] = useHashFilter(billFilterOfHash, billsHref)
  const shown = useMemo(() => filterBills(query.data ?? [], filter), [query.data, filter])
  if (!query.data)
    return (
      <div className="k-card adm-listcard">
        <Loading
          what={t('admin.bills.what')}
          loading
          error={query.error}
          onRetry={() => void query.reload()}
          skeleton={<SkeletonRows rows={4} columns={4} className="adm-sk-rows" />}
        />
      </div>
    )
  const bills = query.data
  // Every filter that has bills, and the one chosen even when it has none; "All" only when it shows more than the
  // current bills (some are canceled).
  const chips = BILL_FILTERS.filter(
    value =>
      value === 'current' ||
      value === filter ||
      (value === 'all' ? filterBills(bills, 'canceled').length > 0 : filterBills(bills, value).length > 0),
  )
  return (
    <>
      {/* Above the card like every list's chips, without counts; only when there is something to pick between. */}
      {chips.length > 1 && (
        <FilterChips label={t('admin.bills.filter.label')}>
          {chips.map(value => (
            <FilterChip key={value} pressed={filter === value} onClick={() => setFilter(value)}>
              {filterLabel(t, value)}
            </FilterChip>
          ))}
        </FilterChips>
      )}
      <AdminList
        rows={shown}
        rowId={b => b.id}
        columns={columns}
        initialSort={{ key: 'created', dir: 'desc' }}
        searchText={b =>
          `${b.owner.email ?? ''} ${b.owner.name ?? ''} ${b.workspaces.map(w => w.name).join(' ')} ${b.id}`
        }
        searchLabel={t('admin.bills.search')}
        label={t('admin.bills.what')}
        onOpen={b => onOpen(b.id)}
        keysRef={keysRef}
        empty={
          bills.length === 0 ? (
            <>
              {t('admin.bills.empty')} <T k="admin.bills.emptyHint" values={{ link: appLink('#admin/access') }} />
            </>
          ) : (
            <>
              {t('admin.bills.filter.empty')}{' '}
              <LinkButton onClick={() => setFilter('all')}>{t('admin.bills.filter.showAll')}</LinkButton>
            </>
          )
        }
      />
    </>
  )
}

// ---- Review ----

const reviewColumns = (t: Translate): Column<AdminReviewRow>[] => [
  {
    key: 'owner',
    label: t('admin.bills.column.owner'),
    render: row => (
      <span className="adm-who">
        <span className="adm-strong">{ownerText(t, row.owner)}</span>
        <span className="adm-sub">{t('admin.bills.workspaceCount', { count: row.workspaces })}</span>
      </span>
    ),
  },
  {
    key: 'status',
    label: t('admin.bills.column.status'),
    render: row =>
      row.heldForReviewAt ? (
        <Badge tone="danger">{t('admin.bills.badge.held')}</Badge>
      ) : (
        <StatusBadge status={row.status} />
      ),
  },
  {
    key: 'risk',
    label: t('admin.bills.review.column.risk'),
    render: row => <RiskBadge level={row.cardRiskLevel} />,
  },
  {
    key: 'since',
    label: t('admin.bills.review.column.since'),
    render: row => <Ago iso={row.heldForReviewAt ?? row.createdAt} />,
  },
]

/** Approve or deny a held bill: the row's quick actions, each asking why in the reason dialog. */
function reviewActions(t: Translate, row: AdminReviewRow): AdminAction[] {
  if (!row.heldForReviewAt) return []
  const decide = (decision: 'approve' | 'deny'): AdminAction => ({
    id: decision,
    label: t(decision === 'approve' ? 'admin.bills.review.approve' : 'admin.bills.review.deny'),
    icon: decision === 'approve' ? 'check' : 'ban',
    tip: t(decision === 'approve' ? 'admin.bills.review.approveText' : 'admin.bills.review.denyText'),
    danger: decision === 'deny',
    run: async () => {},
    dialog: (close, notify) => (
      <ReasonDialog
        title={t(decision === 'approve' ? 'admin.bills.review.approveTitle' : 'admin.bills.review.denyTitle', {
          owner: ownerText(t, row.owner),
        })}
        description={t(decision === 'approve' ? 'admin.bills.review.approveText' : 'admin.bills.review.denyText')}
        submit={t(decision === 'approve' ? 'admin.bills.review.approve' : 'admin.bills.review.deny')}
        danger={decision === 'deny'}
        run={async reason => {
          await runAdmin('billing.reviewHold', { billingAccountId: row.billId, decision, reason })
          await refreshBill(row.billId)
          return t(decision === 'approve' ? 'admin.bills.review.approved' : 'admin.bills.review.denied')
        }}
        notify={notify}
        onClose={close}
      />
    ),
  })
  return [decide('approve'), decide('deny')]
}

/** Billing › Review: the held bills and the new trials, a list like the bills (a row opens its bill). */
function ReviewCard({ onOpen, notify }: { onOpen: (id: string) => void; notify: Notify }) {
  const t = useT()
  const query = useQuery(REVIEW, loadReview)
  const runner = useActionRunner(notify)
  const columns = useMemo(() => reviewColumns(t), [t])
  const rows = query.data ? [...query.data.held, ...query.data.newTrials] : null
  return (
    <ListCard>
      <Loading
        what={t('admin.bills.review.title')}
        loading={!rows}
        error={query.error}
        onRetry={() => void query.reload()}
        skeleton={<SkeletonRows rows={2} columns={4} className="adm-sk-rows" />}
      >
        {rows && (
          <ListTable
            rows={rows}
            rowId={row => row.billId}
            columns={columns}
            label={t('admin.bills.review.title')}
            onOpen={row => onOpen(row.billId)}
            rowActions={
              rows.some(row => row.heldForReviewAt)
                ? row => <RowActions actions={reviewActions(t, row)} onPick={runner.pick} />
                : undefined
            }
            empty={`${t('admin.bills.review.empty')} ${t('admin.bills.review.emptyHint')}`}
          />
        )}
      </Loading>
      {runner.dialog}
    </ListCard>
  )
}

// ---- Stripe events ----

const EVENT_STATE: Record<AdminStripeEvent['state'], MessageKey> = {
  processed: msg('admin.bills.events.state.processed'),
  waiting: msg('admin.bills.events.state.waiting'),
  failed: msg('admin.bills.events.state.failed'),
  unhandled: msg('admin.bills.events.state.unhandled'),
}
const EVENT_TONE: Record<AdminStripeEvent['state'], 'neutral' | 'ok' | 'danger' | 'outline'> = {
  processed: 'ok',
  waiting: 'neutral',
  failed: 'danger',
  unhandled: 'outline',
}
const FILTERS: Record<BillingEventFilter, MessageKey> = {
  all: msg('admin.bills.events.filter.all'),
  waiting: msg('admin.bills.events.filter.waiting'),
  failed: msg('admin.bills.events.filter.failed'),
  unhandled: msg('admin.bills.events.filter.unhandled'),
}

const eventColumns = (t: Translate): Column<AdminStripeEvent>[] => [
  {
    key: 'event',
    label: t('admin.bills.events.column.event'),
    render: e => (
      <span className="adm-who">
        <span className="adm-mono">{e.type}</span>
        <span className="adm-sub adm-mono">
          {e.id}
          {!e.livemode && ` · ${t('admin.bills.events.test')}`}
        </span>
        {e.billId && (
          <span className="adm-sub">
            <AppLink to={`#admin/billing/${encodeURIComponent(e.billId)}`}>{t('admin.bills.events.openBill')}</AppLink>
          </span>
        )}
        {e.lastError && e.state !== 'processed' && <span className="adm-sub">{e.lastError}</span>}
      </span>
    ),
  },
  {
    key: 'state',
    label: t('admin.bills.events.column.state'),
    render: e => <Badge tone={EVENT_TONE[e.state]}>{t(EVENT_STATE[e.state])}</Badge>,
  },
  {
    key: 'received',
    label: t('admin.bills.events.column.received'),
    render: e => <Ago iso={e.receivedAt} />,
  },
  {
    key: 'attempts',
    label: t('admin.bills.events.column.attempts'),
    numeric: true,
    render: e => fmt().number(e.attempts),
  },
]

/**
 * Stripe's events: Billing › Stripe events (`#admin/billing/events`; in the Audit log from LIN-747 to LIN-833). A list
 * like the bills: the states as chips above it (once there are events), Process again as a row's quick action.
 */
function EventsCard({ notify }: { notify: Notify }) {
  const t = useT()
  const [filter, setFilter] = useHashFilter(eventFilterOfHash, eventsHref)
  const query = useQuery(eventsKey(filter), loadEvents(filter))
  const [older, setOlder] = useState<EventsPage | null>(null)
  const runner = useActionRunner(notify)
  const columns = useMemo(() => eventColumns(t), [t])
  const events = query.data ? [...query.data.events, ...(older?.events ?? [])] : null
  const next = older ? older.next : (query.data?.next ?? null)

  async function more() {
    if (!next) return
    try {
      const page = await loadEvents(filter, next)()
      setOlder(previous => ({ events: [...(previous?.events ?? []), ...page.events], next: page.next }))
    } catch (err) {
      notify(errorText(err))
    }
  }
  // Like every billing write, processing an event again asks why (the reason is kept in the audit log).
  const reprocess = (event: AdminStripeEvent): AdminAction[] =>
    event.state === 'processed'
      ? []
      : [
          {
            id: 'reprocess',
            label: t('admin.bills.events.reprocess'),
            icon: 'restart',
            tip: t('admin.bills.events.reprocessTip'),
            run: async () => {},
            dialog: close => (
              <ReasonDialog
                title={t('admin.bills.events.reprocessTitle', { type: event.type })}
                description={t('admin.bills.events.reprocessText')}
                submit={t('admin.bills.events.reprocess')}
                run={async reason => {
                  await runAdmin('billing.reprocessEvent', { eventId: event.id, reason })
                  setOlder(null)
                  await Promise.all([refreshQuery(eventsKey(filter)), refreshQuery(SUMMARY)])
                  return t('admin.bills.events.queued', { type: event.type })
                }}
                notify={notify}
                onClose={close}
              />
            ),
          },
        ]
  // Nothing to filter before Stripe sent anything: the chips wait for the first event.
  const chips = filter !== 'all' || (events?.length ?? 0) > 0
  return (
    <>
      {chips && (
        <FilterChips label={t('admin.bills.events.filter.label')}>
          {(Object.keys(FILTERS) as BillingEventFilter[]).map(value => (
            <FilterChip
              key={value}
              pressed={filter === value}
              onClick={() => {
                setOlder(null)
                setFilter(value)
              }}
            >
              {t(FILTERS[value])}
            </FilterChip>
          ))}
        </FilterChips>
      )}
      <ListCard>
        <Loading
          what={t('admin.bills.events.title')}
          loading={!events}
          error={query.error}
          onRetry={() => void query.reload()}
          skeleton={<SkeletonRows rows={4} columns={4} className="adm-sk-rows" />}
        >
          {events && (
            <ListTable
              rows={events}
              rowId={e => e.id}
              columns={columns}
              label={t('admin.bills.events.title')}
              className="adm-events"
              rowActions={
                events.some(e => e.state !== 'processed')
                  ? e => <RowActions actions={reprocess(e)} onPick={runner.pick} />
                  : undefined
              }
              empty={
                filter === 'all' ? (
                  <T k="admin.bills.events.emptyHow" values={{ link: appLink('#admin/providers/billing') }} />
                ) : (
                  <>
                    {t('admin.bills.events.empty')}{' '}
                    <LinkButton onClick={() => setFilter('all')}>{t('admin.bills.events.showAll')}</LinkButton>
                  </>
                )
              }
            />
          )}
          {next && (
            <div className="adm-list-more">
              <Button size="sm" onClick={() => void more()}>
                {t('admin.bills.events.older')}
              </Button>
            </div>
          )}
        </Loading>
        {runner.dialog}
      </ListCard>
    </>
  )
}

// ---- Stripe Tax ----

/**
 * A switch that acts at once (design principles, rule 5): it shows its new position while it saves and goes back if
 * the save fails; the toast offers Undo, the opposite switch through the same action. Each save asks the server, which
 * still checks the admin's passkey and keeps the change in the audit log.
 */
function useInstantSwitch(save: (on: boolean) => Promise<string>, notify: Notify) {
  const [pending, setPending] = useState<boolean | null>(null)
  async function change(on: boolean) {
    setPending(on)
    try {
      const text = await save(on)
      notify(text, () => save(!on))
    } catch (err) {
      notify(errorText(err))
    } finally {
      setPending(null)
    }
  }
  return { pending, change: (on: boolean) => void change(on) }
}

/**
 * Turns Stripe Tax on or off (`BillingRules.automaticTax`, stored like any billing rule, only this field) and answers
 * the toast, which says what it means for running subscriptions (security review of #1105, M-1). No reason: every
 * admin is still emailed and the audit log keeps who did it (Janik, 2026-11-26). Turned on, it asks Stripe how many
 * paying customers have no billing address, then and only then (review #1105, N-1): `onMissing` gets the count.
 */
export async function setStripeTax(on: boolean, onMissing: (count: number | null) => void = () => {}) {
  const t = i18n().t
  const next = (await runAdmin('billingRules.set', { rules: { automaticTax: on } })) as unknown as BillingRulesData
  setQueryData<BillingRulesData | undefined>(RULES, next, KEPT)
  await refreshQuery(SUMMARY)
  onMissing(null)
  if (on) void loadTaxAddress().then(onMissing, () => onMissing(null))
  return t(on ? 'admin.bills.tax.turnedOn' : 'admin.bills.tax.turnedOff')
}

/** The Stripe Tax switch, a line on Billing's page under the billing switch. */
function TaxLine({ notify }: { notify: Notify }) {
  const t = useT()
  const query = useQuery(RULES, loadRules, KEPT)
  const [missing, setMissing] = useState<number | null>(null)
  const { pending, change } = useInstantSwitch(on => setStripeTax(on, setMissing), notify)
  const on = pending ?? query.data?.effective.automaticTax
  return (
    <section id="adm-stripe-tax" className="k-card k-feature" aria-label={t('admin.bills.rules.automaticTax')}>
      <SettingRow
        title={t('admin.bills.rules.automaticTax')}
        help={t('admin.bills.rules.automaticTax.help')}
        description={t('admin.bills.rules.automaticTax.short')}
        control={
          <Loading
            what={t('admin.bills.rules.automaticTax')}
            loading={on === undefined}
            error={query.error}
            onRetry={() => void query.reload()}
            skeleton={<Skeleton width={34} height={20} className="sk-round" />}
          >
            <Switch
              on={on ?? false}
              onChange={change}
              disabled={pending !== null}
              label={t('admin.bills.rules.automaticTax')}
            />
          </Loading>
        }
      />
      {on && !!missing && (
        <div className="adm-line-notes">
          <Note tone="warning">{t('admin.bills.rules.automaticTax.missing', { count: missing })}</Note>
        </div>
      )}
    </section>
  )
}

// ---- Self-serve sign-up ----

/** Turns self-serve sign-up on or off and answers the toast. No reason: every server admin is still emailed. */
export async function setSelfServe(on: boolean) {
  const t = i18n().t
  const saved = (await runAdmin('signup.setSelfServe', { on })) as unknown as SelfServeData
  setQueryData<SelfServeData | undefined>(SELF_SERVE, saved, KEPT)
  await refreshQuery(SUMMARY)
  return t(saved.on ? 'admin.bills.selfServe.turnedOn' : 'admin.bills.selfServe.turnedOff')
}

/**
 * Self-serve sign-up as a line of its own on Sign-up & access: the switch and whether sign-up is really open. Switched
 * on is not open while something it needs is missing (billing through Stripe, the Turnstile keys while the bot check is
 * on, the terms), and the line says so plainly under it. The switch acts at once with Undo; every server admin is
 * emailed, and turning it on needs the passkey (billing-admin's money check).
 */
export function SelfServeCard({ notify }: { notify: Notify }) {
  const t = useT()
  const query = useQuery(SELF_SERVE, loadSelfServe, KEPT)
  const { pending, change } = useInstantSwitch(setSelfServe, notify)
  const data = query.data
  const link = { link: appLink('#admin/billing') }
  // Switched on but closed (a key or the terms missing) needs the admin: a red badge next to the switch, the reason
  // below. Its words never say it is open while it is not (they say what the switch does).
  const closedWhileOn = !!data?.on && !data.open
  return (
    <section className="k-card k-feature" aria-label={t('admin.bills.selfServe.switch')}>
      <SettingRow
        title={t('admin.bills.selfServe.switch')}
        description={
          data && !data.billingInEffect && !data.on ? (
            <T k="admin.bills.selfServe.needsBillingLink" values={link} />
          ) : data?.open ? (
            t('admin.bills.selfServe.openNow')
          ) : (
            t('admin.signupPage.selfServe.summary')
          )
        }
        control={
          <Loading
            what={t('admin.bills.selfServe.switch')}
            loading={!data}
            error={query.error}
            onRetry={() => void query.reload()}
            skeleton={<Skeleton width={34} height={20} className="sk-round" />}
          >
            {closedWhileOn && <Badge tone="danger">{t('admin.bills.selfServe.state.closed')}</Badge>}
            <Switch
              on={pending ?? data?.on ?? false}
              onChange={change}
              label={t('admin.bills.selfServe.switch')}
              // Off always works; on needs billing through Stripe in effect and the terms set (A9).
              disabled={
                !data || pending !== null || (!data.on && (!data.billingInEffect || data.termsMissing.length > 0))
              }
            />
          </Loading>
        }
      />
      {data && (closedWhileOn || data.termsMissing.length > 0) && (
        <div className="adm-line-notes">
          {data?.on && data.closedBecause === 'bot_check_missing' && (
            <Note tone="danger">
              <T k="admin.bills.selfServe.closed.botCheck" values={{ link: appLink('#admin/providers/bot_check') }} />
            </Note>
          )}
          {data?.on && data.closedBecause === 'billing_not_in_effect' && (
            <Note tone="danger">
              <T k="admin.bills.selfServe.closed.billing" values={link} />
            </Note>
          )}
          {data && data.termsMissing.length > 0 && (
            <Note tone={data.on ? 'danger' : 'warning'}>
              {t(data.on ? 'admin.bills.selfServe.termsMissingOn' : 'admin.bills.selfServe.termsMissing', {
                vars: data.termsMissing.join(', '),
              })}
            </Note>
          )}
        </div>
      )}
    </section>
  )
}

// ---- One number field of the rules and limits editors ----

const UNIT_END: Partial<Record<FieldUnit, MessageKey>> = {
  usdPerMinute: msg('admin.bills.unit.perMinute'),
  usdPerMonth: msg('admin.bills.unit.perMonth'),
  usdPerYear: msg('admin.bills.unit.perYear'),
  minutes: msg('admin.bills.unit.minutes'),
  days: msg('admin.bills.unit.days'),
  seconds: msg('admin.bills.unit.seconds'),
  calls: msg('admin.bills.unit.calls'),
}

type NumberFieldProps = {
  id: string
  label: string
  /** The detail behind the (?): what the field does, and the server's limit for it. */
  help?: string
  value: string
  /** The field's default, as the form holds it ("11"), and as the page says it ("$11.00"). */
  fallback: string
  fallbackText: string
  unit: FieldUnit | null
  error: string | null
  /** Empty is a value of its own (none), not the default: no default as the placeholder. */
  blankIsNone?: boolean
  onChange: (value: string) => void
}

/**
 * A number with its unit inside the field and its default as the placeholder: an empty field takes the default. A
 * value of its own shows the default and a Reset beside the label, so the install's own values stand out.
 */
function NumberField(props: NumberFieldProps) {
  const { id, label, help, value, fallback, fallbackText, unit, error, blankIsNone: blankNone, onChange } = props
  const t = useT()
  const own = (value.trim() !== '' || !!blankNone) && !sameText(value, fallback)
  const end = unit && UNIT_END[unit]
  const money = unit === 'usd' || unit === 'usdPerMonth' || unit === 'usdPerYear' || unit === 'usdPerMinute'
  return (
    <FormField
      id={id}
      label={label}
      help={help}
      error={error}
      className={cx(own && 'adm-own')}
      aside={
        own ? (
          <span className="adm-default">
            {t('admin.bills.rules.default', { value: fallbackText || EMPTY })}
            {' · '}
            <LinkButton title={t('admin.bills.rules.resetTip')} onClick={() => onChange(fallback)}>
              {t('admin.bills.rules.reset')}
            </LinkButton>
          </span>
        ) : null
      }
    >
      <Input
        id={id}
        inputMode="decimal"
        size="sm"
        value={value}
        placeholder={blankNone ? undefined : fallback}
        invalid={!!error}
        start={money ? <span className="adm-unit">{usdSymbol()}</span> : undefined}
        end={end ? <span className="adm-unit">{t(end)}</span> : undefined}
        onChange={e => onChange(e.target.value)}
      />
    </FormField>
  )
}

// ---- Sign-up limits ----

const SIGNUP_LABELS: Record<SignupCountRule, [MessageKey, MessageKey]> = {
  codesPerAddressHour: [
    msg('admin.bills.signupRules.field.codesPerAddressHour'),
    msg('admin.bills.signupRules.field.codesPerAddressHour.help'),
  ],
  codesPerAddressDay: [
    msg('admin.bills.signupRules.field.codesPerAddressDay'),
    msg('admin.bills.signupRules.field.codesPerAddressDay.help'),
  ],
  signupsPerIpHour: [
    msg('admin.bills.signupRules.field.signupsPerIpHour'),
    msg('admin.bills.signupRules.field.signupsPerIpHour.help'),
  ],
  signupsPerIpDay: [
    msg('admin.bills.signupRules.field.signupsPerIpDay'),
    msg('admin.bills.signupRules.field.signupsPerIpDay.help'),
  ],
  codesPerInstallHour: [
    msg('admin.bills.signupRules.field.codesPerInstallHour'),
    msg('admin.bills.signupRules.field.codesPerInstallHour.help'),
  ],
  pendingDays: [
    msg('admin.bills.signupRules.field.pendingDays'),
    msg('admin.bills.signupRules.field.pendingDays.help'),
  ],
  trialWorkspacesCloud: [
    msg('admin.bills.signupRules.field.trialWorkspacesCloud'),
    msg('admin.bills.signupRules.field.trialWorkspacesCloud.help'),
  ],
  trialNumbersPerWorkspace: [
    msg('admin.bills.signupRules.field.trialNumbersPerWorkspace'),
    msg('admin.bills.signupRules.field.trialNumbersPerWorkspace.help'),
  ],
}
const SIGNUP_GROUP_TITLES: Record<(typeof SIGNUP_GROUPS)[number]['id'], [MessageKey, MessageKey]> = {
  codes: [msg('admin.bills.signupRules.group.codes'), msg('admin.bills.signupRules.group.codes.text')],
  trial: [msg('admin.bills.signupRules.group.trial'), msg('admin.bills.signupRules.group.trial.text')],
}

/**
 * A group of the sign-up limits: a card of its own, or under the Sign-up limits line (CardInline) a heading in the
 * form, so the group keeps its name.
 */
function RulesGroup({
  title,
  text,
  help,
  children,
}: {
  title: string
  text: string
  help?: string
  children: ReactNode
}) {
  if (useContext(CardInline))
    return (
      <div className="adm-rules-sub">
        <b>
          {title}
          {help && <HelpTip text={help} />}
        </b>
        <span className="help">{text}</span>
        {children}
      </div>
    )
  return (
    <Card title={title} description={text} help={help} className="adm-detail">
      {children}
    </Card>
  )
}

/** The install's sign-up limits (`signup.rules`), in groups, saved together from one bar. */
export function SignupRulesCard({ notify }: { notify: Notify }) {
  const t = useT()
  const query = useQuery(SELF_SERVE, loadSelfServe, KEPT)
  const data = query.data
  const saved = useMemo(() => (data ? signupForm(data.rules) : null), [data])
  const [form, setForm] = useState<SignupForm | null>(saved)
  const [problems, setProblems] = useState<string[]>([])
  const [asking, setAsking] = useState<Record<string, unknown> | null>(null)
  useEffect(() => {
    if (saved) setForm(saved)
  }, [saved])
  const dirty = !!form && !!saved && signupDirty(form, saved)
  // Turning the bot check off loosens sign-up most: the confirmation says so and the button is red.
  const botCheckOff = !!data?.rules.turnstile && form?.turnstile === false

  function save(e: FormEvent) {
    e.preventDefault()
    if (!data || !form) return
    const parsed = signupFromForm(form, data.defaults)
    setProblems(parsed.problems)
    if ('rules' in parsed) setAsking(parsed.rules)
  }
  const setCount = (field: SignupCountRule, value: string) =>
    setForm(f => f && { ...f, counts: { ...f.counts, [field]: value } })
  const toggleLevel = (level: string, on: boolean) =>
    setForm(
      f =>
        f && {
          ...f,
          reviewRiskLevels: on
            ? [...f.reviewRiskLevels.filter(l => l !== level), level]
            : f.reviewRiskLevels.filter(l => l !== level),
        },
    )
  const loading = (
    <Loading
      what={t('admin.bills.signupRules.title')}
      loading
      error={query.error}
      onRetry={() => void query.reload()}
      skeleton={<SkeletonRows rows={4} columns={2} />}
    />
  )
  if (!data || !form)
    return (
      <Card title={t('admin.bills.signupRules.title')} className="adm-detail">
        {loading}
      </Card>
    )
  return (
    <form onSubmit={save} onKeyDown={e => onSaveKey(e, dirty)} className="adm-rules">
      <Card
        title={t('admin.bills.signupRules.title')}
        description={t('admin.bills.signupRules.descriptionShort')}
        help={t('admin.bills.signupRules.description')}
        className="adm-detail"
      >
        {data.problems.length > 0 && (
          <Note tone="warning">{t('admin.bills.signupRules.ignored', { fields: data.problems.join(', ') })}</Note>
        )}
        <SettingRow
          title={t('admin.bills.signupRules.turnstile')}
          help={t('admin.bills.signupRules.turnstile.help')}
          description={
            form.turnstile &&
            !data.turnstileReady && (
              <T
                k="admin.bills.signupRules.turnstile.noKeys"
                values={{ link: appLink('#admin/providers/bot_check') }}
              />
            )
          }
          control={
            <Switch
              on={form.turnstile}
              onChange={on => setForm(f => f && { ...f, turnstile: on })}
              label={t('admin.bills.signupRules.turnstile')}
            />
          }
        />
        {!form.turnstile && <Note tone="warning">{t('admin.bills.signupRules.turnstile.offWarning')}</Note>}
        <FormField
          id="adm-signup-domains"
          label={t('admin.bills.signupRules.blockedDomains')}
          help={t('admin.bills.signupRules.blockedDomains.help')}
        >
          <Textarea
            id="adm-signup-domains"
            rows={2}
            value={form.blockedDomains}
            placeholder={t('admin.bills.signupRules.blockedDomains.placeholder')}
            onChange={e => setForm(f => f && { ...f, blockedDomains: e.target.value })}
          />
        </FormField>
      </Card>
      {SIGNUP_GROUPS.map(group => {
        const [title, text] = SIGNUP_GROUP_TITLES[group.id]
        return (
          <RulesGroup key={group.id} title={t(title)} text={t(text)}>
            <div className="adm-rules-grid">
              {group.fields.map(field => {
                const [min, max] = SIGNUP_RULE_RANGES[field]
                const [label, help] = SIGNUP_LABELS[field]
                const fallback = String(data.defaults[field])
                return (
                  <NumberField
                    key={field}
                    id={`adm-signup-${field}`}
                    label={t(label)}
                    help={`${t(help)} ${t('admin.bills.signupRules.range', { min, max })}`}
                    value={form.counts[field]}
                    fallback={fallback}
                    fallbackText={fmt().number(data.defaults[field])}
                    unit={field === 'pendingDays' ? 'days' : null}
                    error={problems.includes(field) ? t('admin.bills.signupRules.notInRange', { min, max }) : null}
                    onChange={value => setCount(field, value)}
                  />
                )
              })}
            </div>
          </RulesGroup>
        )
      })}
      <RulesGroup
        title={t('admin.bills.signupRules.reviewRiskLevels')}
        text={t('admin.bills.signupRules.reviewRiskLevels.short')}
        help={t('admin.bills.signupRules.reviewRiskLevels.help')}
      >
        <fieldset className="adm-checks adm-checks-row">
          <legend className="sr-only">{t('admin.bills.signupRules.reviewRiskLevels')}</legend>
          {/* Elevated and Highest; Not assessed and Unknown only while one of them is ticked (so it can be unticked). */}
          {RADAR_RISK_LEVELS.filter(
            level =>
              level === 'elevated' ||
              level === 'highest' ||
              (level !== 'normal' && !!saved?.reviewRiskLevels.includes(level)),
          ).map(level => (
            <Checkbox
              key={level}
              checked={form.reviewRiskLevels.includes(level)}
              onChange={on => toggleLevel(level, on)}
            >
              {t(RISK[level])}
            </Checkbox>
          ))}
        </fieldset>
      </RulesGroup>
      <SaveBar
        dirty={dirty}
        onCancel={() => {
          setProblems([])
          if (saved) setForm(saved)
        }}
        label={t('admin.bills.signupRules.save')}
        note={t('admin.bills.rules.unsaved', { count: saved ? signupChanges(form, saved) : 0 })}
      />
      {asking && (
        <ReasonDialog
          title={t('admin.bills.signupRules.confirmTitle')}
          description={t(
            botCheckOff ? 'admin.bills.signupRules.confirmBotCheckOff' : 'admin.bills.signupRules.confirmText',
          )}
          danger={botCheckOff}
          submit={t('admin.bills.signupRules.save')}
          run={async reason => {
            const next = (await runAdmin('signup.setRules', { rules: asking, reason })) as unknown as SelfServeData
            setQueryData<SelfServeData | undefined>(SELF_SERVE, next, KEPT)
            await refreshQuery(SUMMARY)
            return t('admin.bills.signupRules.saved')
          }}
          notify={notify}
          onClose={() => setAsking(null)}
        />
      )}
    </form>
  )
}

// ---- Billing rules ----

/** Each rule's plain label and its detail behind the (?). */
const RULE_LABELS: Record<RuleField, MessageKey> = {
  workspaceMonthlyCents: msg('admin.bills.rules.field.workspaceMonthlyCents'),
  workspaceYearlyCents: msg('admin.bills.rules.field.workspaceYearlyCents'),
  partnerMonthlyCents: msg('admin.bills.rules.field.partnerMonthlyCents'),
  partnerYearlyCents: msg('admin.bills.rules.field.partnerYearlyCents'),
  trialDays: msg('admin.bills.rules.field.trialDays'),
  includedStandardSeconds: msg('admin.bills.rules.field.includedStandardSeconds'),
  balanceBufferMicros: msg('admin.bills.rules.field.balanceBufferMicros'),
  concurrentCallsBase: msg('admin.bills.rules.field.concurrentCallsBase'),
  concurrentCallsPerWorkspace: msg('admin.bills.rules.field.concurrentCallsPerWorkspace'),
  concurrentCallsMaxPerWorkspace: msg('admin.bills.rules.field.concurrentCallsMaxPerWorkspace'),
  extraCallCents: msg('admin.bills.rules.field.extraCallCents'),
  trialConcurrentCalls: msg('admin.bills.rules.field.trialConcurrentCalls'),
  billedTransferCapSeconds: msg('admin.bills.rules.field.billedTransferCapSeconds'),
  callLimitGraceSeconds: msg('admin.bills.rules.field.callLimitGraceSeconds'),
  extraNumberCents: msg('admin.bills.rules.field.extraNumberCents'),
  rechargeCapPerWorkspaceCents: msg('admin.bills.rules.field.rechargeCapPerWorkspaceCents'),
}

// Each card: its title, its lede and one (?) after the title for what only some admins need (rule 16); no (?) per field.
const GROUP_TITLES: Record<RuleGroupId, [MessageKey, MessageKey, MessageKey]> = {
  plans: [
    msg('admin.bills.rules.group.plans'),
    msg('admin.bills.rules.group.plans.text'),
    msg('admin.bills.rules.group.plans.help'),
  ],
  minutes: [
    msg('admin.bills.rules.group.minutes'),
    msg('admin.bills.rules.group.minutes.text'),
    msg('admin.bills.rules.group.minutes.help'),
  ],
  trial: [
    msg('admin.bills.rules.group.trial'),
    msg('admin.bills.rules.group.trial.text'),
    msg('admin.bills.rules.group.trial.help'),
  ],
  concurrency: [
    msg('admin.bills.rules.group.concurrency'),
    msg('admin.bills.rules.group.concurrency.text'),
    msg('admin.bills.rules.group.concurrency.help'),
  ],
  limits: [
    msg('admin.bills.rules.group.limits'),
    msg('admin.bills.rules.group.limits.text'),
    msg('admin.bills.rules.group.limits.help'),
  ],
}

const LEVEL_NAMES: Record<string, MessageKey> = {
  standard: msg('admin.bills.rules.levelName.standard'),
  premium: msg('admin.bills.rules.levelName.premium'),
  ultra: msg('admin.bills.rules.levelName.ultra'),
}

function RulesCard({ notify }: { notify: Notify }) {
  const t = useT()
  const query = useQuery(RULES, loadRules, KEPT)
  const data = query.data
  // A level that is off on this server (Call quality) has no price to set: its fields wait until it is on. Shown while
  // that is not read yet; Standard is always on.
  const levels = useQuery(CALL_QUALITY, loadCallQuality).data?.levels
  const levelShown = (level: string) => levels?.find(l => l.level === level)?.enabled ?? true
  const saved = useMemo(() => (data ? rulesForm(data.effective) : null), [data])
  const defaults = useMemo(() => (data ? rulesForm(data.defaults) : null), [data])
  const [form, setForm] = useState<RulesForm>({})
  const [problems, setProblems] = useState<string[]>([])
  const [asking, setAsking] = useState<Record<string, unknown> | null>(null)
  useEffect(() => {
    if (saved) setForm(saved)
  }, [saved])
  const changes = saved ? changedFields(form, saved).length : 0
  const dirty = changes > 0

  function save(e: FormEvent) {
    e.preventDefault()
    if (!data) return
    const parsed = rulesFromForm(form, data.defaults)
    setProblems(parsed.problems)
    if ('rules' in parsed) setAsking(parsed.rules)
  }
  if (!data || !defaults)
    return (
      <Card title={t('admin.bills.rules.title')} className="adm-detail">
        <Loading
          what={t('admin.bills.rules.title')}
          loading
          error={query.error}
          onRetry={() => void query.reload()}
          skeleton={<SkeletonRows rows={4} columns={2} />}
        />
      </Card>
    )
  const field = (key: string, label: string, fallbackText?: string) => (
    <NumberField
      key={key}
      id={`adm-rule-${key}`}
      label={label}
      value={form[key] ?? ''}
      fallback={defaults[key] ?? ''}
      fallbackText={fallbackText ?? defaultText(key, defaults[key] ?? '')}
      unit={ruleUnit(key)}
      blankIsNone={blankIsNone(key)}
      error={problems.includes(key) ? t('admin.bills.rules.notANumber') : null}
      onChange={value => setForm(f => ({ ...f, [key]: value }))}
    />
  )
  const ruleField = (key: RuleField) => {
    return field(key, t(RULE_LABELS[key]))
  }
  return (
    <form onSubmit={save} onKeyDown={e => onSaveKey(e, dirty)} className="adm-rules">
      {data.problems.length > 0 && (
        <Note tone="warning">{t('admin.bills.rules.ignored', { fields: data.problems.join(', ') })}</Note>
      )}
      {RULE_GROUPS.map(group => {
        const [title, text, help] = GROUP_TITLES[group.id]
        // The server's floor is a limit Save refuses to go under: in the lede, not behind the (?).
        const floor = rulesFloorText(group.id, data.minPlanCents, data.minMicrosPerMinute)
        return (
          <Card
            key={group.id}
            id={`adm-rules-${group.id}`}
            title={t(title)}
            description={floor ? `${t(text)} ${floor}` : t(text)}
            help={t(help)}
            className="adm-detail"
          >
            {group.id === 'minutes' && (
              <div className="adm-rules-levels">
                {Object.entries(data.defaults.levels)
                  .filter(([level]) => levelShown(level))
                  .map(([level, fallback]) => {
                    const name = LEVEL_NAMES[level] ? t(LEVEL_NAMES[level]) : level
                    return (
                      <div key={level} className="adm-rules-grid">
                        {field(
                          `levels.${level}.price`,
                          t('admin.bills.rules.levelPrice', { level: name }),
                          rateOfMicros(fallback.microsPerMinute),
                        )}
                        {field(`levels.${level}.factor`, t('admin.bills.rules.levelFactor', { level: name }))}
                      </div>
                    )
                  })}
              </div>
            )}
            <div className="adm-rules-grid">{group.fields.map(key => ruleField(key))}</div>
          </Card>
        )
      })}
      <SaveBar
        dirty={dirty}
        onCancel={() => {
          setProblems([])
          if (saved) setForm(saved)
        }}
        label={t('admin.bills.rules.save')}
        note={t('admin.bills.rules.unsaved', { count: changes })}
      />
      {asking && (
        <ReasonDialog
          title={t('admin.bills.rules.confirmTitle')}
          description={t('admin.bills.rules.confirmText')}
          submit={t('admin.bills.rules.save')}
          run={async reason => {
            const next = (await runAdmin('billingRules.set', { rules: asking, reason }).catch(err => {
              if ((err as { code?: string }).code !== PLAN_PRICE_FLOOR) throw err
              throw new Error(t('admin.bills.rules.planFloor', { amount: usdOfCents(data?.minPlanCents ?? 0) }))
            })) as unknown as BillingRulesData
            setQueryData<BillingRulesData | undefined>(RULES, next, KEPT)
            await refreshQuery(SUMMARY)
            return t('admin.bills.rules.saved')
          }}
          notify={notify}
          onClose={() => setAsking(null)}
        />
      )}
    </form>
  )
}

// ---- One bill ----

type Open =
  | { kind: 'credit'; rechargeId?: string; amountCents?: number }
  | { kind: 'refund' }
  | { kind: 'status'; status: 'comped' | 'suspended' | 'active' }
  | { kind: 'cap' }
  | { kind: 'concurrency' }
  | { kind: 'owner' }
  | { kind: 'move' }
  | { kind: 'attach' }

const LEDGER_KIND: Record<AdminBillDetail['ledger'][number]['kind'], MessageKey> = {
  usage: msg('admin.bills.ledger.kind.usage'),
  number: msg('admin.bills.ledger.kind.number'),
  recharge: msg('admin.bills.ledger.kind.recharge'),
  topup: msg('admin.bills.ledger.kind.topup'),
  refund: msg('admin.bills.ledger.kind.refund'),
  credit: msg('admin.bills.ledger.kind.credit'),
  adjustment: msg('admin.bills.ledger.kind.adjustment'),
  writeoff: msg('admin.bills.ledger.kind.writeoff'),
}

/** The Stripe customer's name (else its email) with the email under it; nothing when Stripe did not say. */
function StripeCustomer({
  contact,
  loading,
}: {
  contact: AdminBillCustomer['customer'] | undefined
  loading: boolean
}) {
  if (loading) return <SkeletonText width={140} className="adm-line" />
  if (!contact || (!contact.name && !contact.email)) return null
  return (
    <>
      <span className="adm-line">{contact.name ?? contact.email}</span>
      {contact.name && contact.email && <span className="adm-sub">{contact.email}</span>}
    </>
  )
}

/**
 * What an admin can do to a bill, only what can run now (Resume a comped or suspended one, never Comp it again), and
 * why the others can't. Credit and Refund are buttons in the page header, the rest in its ⋯ menu.
 */
export function billActions(t: Translate, bill: AdminBillDetail, open: (what: Open) => void): AdminAction[] {
  const canceled = bill.status === 'canceled'
  return [
    {
      id: 'credit',
      label: t('admin.bills.action.credit'),
      icon: 'plus',
      tip: t('admin.bills.action.creditTip'),
      run: async () => open({ kind: 'credit' }),
    },
    {
      id: 'refund',
      label: t('admin.bills.action.refund'),
      icon: 'reply',
      tip: t('admin.bills.action.refundTip'),
      disabledReason: !bill.dashboardUrl
        ? t('admin.bills.action.needsStripe')
        : !bill.refundable.some(p => p.creditedMicros > p.refundedMicros)
          ? t('admin.bills.action.nothingToRefund')
          : undefined,
      run: async () => open({ kind: 'refund' }),
    },
    ...(bill.status === 'comped' || bill.status === 'suspended'
      ? [
          {
            id: 'resume',
            label: t('admin.bills.action.resume'),
            icon: 'restart' as const,
            tip: t('admin.bills.action.resumeTip'),
            run: async () => open({ kind: 'status', status: 'active' }),
          },
        ]
      : []),
    ...(!canceled && bill.status !== 'comped'
      ? [
          {
            id: 'comp',
            menu: true,
            label: t('admin.bills.action.comp'),
            icon: 'star' as const,
            tip: t('admin.bills.action.compTip'),
            run: async () => open({ kind: 'status', status: 'comped' }),
          },
        ]
      : []),
    ...(!canceled && bill.status !== 'suspended'
      ? [
          {
            id: 'suspend',
            menu: true,
            label: t('admin.bills.action.suspend'),
            icon: 'ban' as const,
            tip: t('admin.bills.action.suspendTip'),
            danger: true,
            run: async () => open({ kind: 'status', status: 'suspended' }),
          },
        ]
      : []),
    {
      id: 'cap',
      menu: true,
      label: t('admin.bills.action.cap'),
      icon: 'pencil',
      tip: t('admin.bills.action.capTip'),
      run: async () => open({ kind: 'cap' }),
    },
    {
      id: 'concurrency',
      menu: true,
      label: t('admin.bills.action.concurrency'),
      icon: 'phone',
      tip: t('admin.bills.action.concurrencyTip'),
      run: async () => open({ kind: 'concurrency' }),
    },
    {
      id: 'owner',
      menu: true,
      label: t('admin.bills.action.owner'),
      icon: 'user',
      tip: t('admin.bills.action.ownerTip'),
      disabledReason: bill.members.length < 2 ? t('admin.bills.action.noOtherMember') : undefined,
      run: async () => open({ kind: 'owner' }),
    },
    {
      id: 'move',
      menu: true,
      label: t('admin.bills.action.move'),
      icon: 'move',
      tip: t('admin.bills.action.moveTip'),
      disabledReason: !bill.workspaces.length
        ? t('admin.bills.noWorkspaces')
        : !bill.otherBills.some(b => b.status !== 'canceled')
          ? t('admin.bills.action.noOtherBill')
          : undefined,
      run: async () => open({ kind: 'move' }),
    },
    {
      id: 'attach',
      menu: true,
      label: t('admin.bills.action.attach'),
      icon: 'plus',
      tip: t('admin.bills.action.attachTip'),
      disabledReason: !bill.unbilledWorkspaces.length ? t('admin.bills.action.noUnbilled') : undefined,
      run: async () => open({ kind: 'attach' }),
    },
  ]
}

function BillDetail({ id, notify, slot }: { id: string; notify: Notify; slot: HTMLElement | null }) {
  const t = useT()
  const query = useQuery(billKey(id), loadBill(id))
  const [open, setOpen] = useState<Open | null>(null)
  const bill = query.data
  // The Stripe customer's name and email, asked of Stripe on its own so the page never waits for it.
  const customer = useQuery(bill?.stripeCustomerId ? customerKey(id) : null, loadCustomer(id))
  if (!bill)
    return (
      <div className="k-card">
        <Loading
          what={t('admin.bills.detail.what')}
          loading
          error={query.error}
          onRetry={() => void query.reload()}
          skeleton={<SkeletonRows rows={6} columns={2} />}
        />
      </div>
    )
  const actions = billActions(t, bill, setOpen)
  const stripe = (path: string) => (bill.dashboardUrl ? `${bill.dashboardUrl}/${path}` : null)
  // The extra calls at the same time the owner bought (LIN-450), over the bill's workspaces.
  const extraCalls = bill.workspaces.reduce((sum, w) => sum + w.extraCalls, 0)
  const done = async (text: string) => {
    await refreshBill(id)
    return text
  }

  return (
    <>
      <DetailActions
        actions={actions}
        onPick={a => {
          void a.run()
        }}
        slot={slot}
      />
      <Card title={t('admin.bills.detail.facts')} className="adm-detail">
        <dl className="adm-facts">
          <Fact label={t('admin.bills.column.status')}>
            <StatusBadge status={bill.status} />
            {bill.suspendReason && (
              <span className="adm-sub">{t('admin.bills.suspendReason', { reason: bill.suspendReason })}</span>
            )}
            {bill.heldForReviewAt && (
              <span className="adm-sub">{t('admin.bills.heldSince', { when: when(bill.heldForReviewAt) })}</span>
            )}
          </Fact>
          <Fact label={t('admin.bills.fact.risk')}>
            <RiskBadge level={bill.cardRiskLevel} />
            <span className="adm-sub">{t('admin.bills.fact.riskHelp')}</span>
          </Fact>
          <Fact label={t('admin.bills.fact.plan')}>
            {t(bill.kind === 'partner' ? 'admin.bills.kind.partner' : 'admin.bills.kind.cloud')}
            {' · '}
            {t(bill.interval === 'year' ? 'admin.bills.interval.year' : 'admin.bills.interval.month')}
          </Fact>
          <Fact label={t('admin.bills.column.owner')}>
            <AppLink to={`#admin/users/${encodeURIComponent(bill.owner.id)}`}>{ownerText(t, bill.owner)}</AppLink>
          </Fact>
          <Fact label={t('admin.bills.column.balance')}>
            {usdOfMicros(bill.balanceMicros)}
            {bill.reservedMicros > 0 && (
              <span className="adm-sub">{t('admin.bills.reserved', { amount: usdOfMicros(bill.reservedMicros) })}</span>
            )}
          </Fact>
          <Fact label={t('admin.bills.fact.period')}>
            {bill.currentPeriodStart && bill.currentPeriodEnd
              ? t('admin.bills.fact.periodRange', {
                  from: day(bill.currentPeriodStart),
                  to: day(bill.currentPeriodEnd),
                })
              : EMPTY}
            {bill.trialEndsAt && (
              <span className="adm-sub">{t('admin.bills.fact.trialEnds', { when: day(bill.trialEndsAt) })}</span>
            )}
          </Fact>
          <Fact label={t('admin.bills.fact.recharge')}>
            {bill.autoRecharge
              ? t('admin.bills.fact.rechargeOn', {
                  amount: usdOfCents(bill.rechargeAmountCents),
                  threshold: usdOfCents(bill.rechargeThresholdCents),
                })
              : t('admin.bills.fact.rechargeOff')}
            {bill.rechargeFailedAt && (
              <span className="adm-sub">
                {t('admin.bills.fact.rechargeFailed', { when: when(bill.rechargeFailedAt) })}
              </span>
            )}
          </Fact>
          <Fact label={t('admin.bills.fact.cap')}>
            {t('admin.bills.fact.capValue', {
              cap: usdOfCents(bill.rechargeCapCents),
              base: usdOfCents(bill.rechargeCapBaseCents),
            })}
          </Fact>
          <Fact label={t('admin.bills.fact.concurrency')}>
            {bill.concurrentCallsCap === null
              ? t('admin.bills.fact.concurrencyRules', { count: bill.rulesConcurrentCalls })
              : t('admin.bills.fact.concurrencySet', { count: bill.concurrentCallsCap })}
            {extraCalls > 0 && (
              <span className="adm-sub">{t('admin.bills.fact.concurrencyExtra', { count: extraCalls })}</span>
            )}
          </Fact>
          <Fact label={t('admin.bills.fact.stripe')}>
            {bill.stripeCustomerId && (
              <StripeCustomer contact={customer.data} loading={customer.data === undefined && !customer.error} />
            )}
            {bill.stripeCustomerId && stripe(`customers/${bill.stripeCustomerId}`) ? (
              <span className="adm-line">
                <a href={stripe(`customers/${bill.stripeCustomerId}`)!} target="_blank" rel="noreferrer">
                  {t('admin.bills.fact.customer')}
                </a>
                {bill.stripeSubscriptionId && (
                  <>
                    {' · '}
                    <a href={stripe(`subscriptions/${bill.stripeSubscriptionId}`)!} target="_blank" rel="noreferrer">
                      {t('admin.bills.fact.subscription')}
                    </a>
                  </>
                )}
              </span>
            ) : (
              t('admin.bills.fact.noStripe')
            )}
          </Fact>
          <Fact label={t('admin.bills.column.created')}>{day(bill.createdAt)}</Fact>
        </dl>
      </Card>

      <Card
        title={t('admin.bills.usage.title')}
        description={t('admin.bills.usage.description')}
        className="adm-detail"
      >
        {bill.workspaces.length ? (
          <div className="adm-scroll">
            <table className="adm-table adm-stack">
              <thead>
                <tr>
                  <th scope="col">{t('admin.bills.usage.workspace')}</th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.usage.minutes')}
                  </th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.usage.paid')}
                  </th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.usage.extraCalls')}
                  </th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.usage.busyCallers')} <HelpTip text={t('admin.bills.usage.busyCallersHelp')} />
                  </th>
                </tr>
              </thead>
              <tbody>
                {bill.workspaces.map(w => {
                  const used = bill.usage.find(u => u.workspaceId === w.id)
                  return (
                    <tr key={w.id}>
                      <th scope="row" data-label={t('admin.bills.usage.workspace')}>
                        <AppLink to={`#admin/workspaces/${encodeURIComponent(w.id)}`}>{w.name}</AppLink>
                      </th>
                      <td className="adm-num" data-label={t('admin.bills.usage.minutes')}>
                        {fmt().number((used?.seconds ?? 0) / 60, { maximumFractionDigits: 1 })}
                      </td>
                      <td className="adm-num" data-label={t('admin.bills.usage.paid')}>
                        {usdOfMicros(used?.paidMicros ?? 0)}
                      </td>
                      <td className="adm-num" data-label={t('admin.bills.usage.extraCalls')}>
                        {w.extraCalls ? t('admin.bills.usage.extraCallsValue', { count: w.extraCalls }) : EMPTY}
                      </td>
                      <td className="adm-num" data-label={t('admin.bills.usage.busyCallers')}>
                        {w.busyCallers ? fmt().number(w.busyCallers) : EMPTY}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <ListEmpty>{t('admin.bills.noWorkspaces')}</ListEmpty>
        )}
      </Card>

      <Card
        title={t('admin.bills.ledger.title')}
        description={t('admin.bills.ledger.description')}
        className="adm-detail"
      >
        {bill.ledger.length ? (
          <div className="adm-scroll">
            <table className="adm-table adm-stack">
              <thead>
                <tr>
                  <th scope="col">{t('admin.bills.ledger.column.when')}</th>
                  <th scope="col">{t('admin.bills.ledger.column.kind')}</th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.ledger.column.amount')}
                  </th>
                  <th scope="col">{t('admin.bills.ledger.column.note')}</th>
                </tr>
              </thead>
              <tbody>
                {bill.ledger.map(e => (
                  <tr key={e.id}>
                    <td data-label={t('admin.bills.ledger.column.when')}>{when(e.createdAt)}</td>
                    <th scope="row" data-label={t('admin.bills.ledger.column.kind')}>
                      {t(LEDGER_KIND[e.kind])}
                      {e.seconds !== null && (
                        <span className="adm-sub">
                          {t('admin.bills.ledger.seconds', { count: e.seconds, level: e.priceBasis ?? EMPTY })}
                        </span>
                      )}
                    </th>
                    <td className="adm-num" data-label={t('admin.bills.ledger.column.amount')}>
                      {usdOfMicros(e.amountMicros)}
                    </td>
                    <td data-label={t('admin.bills.ledger.column.note')}>
                      {e.note ?? EMPTY}
                      {e.actor && <span className="adm-sub">{e.actor.email ?? e.actor.id}</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <ListEmpty>{t('admin.bills.ledger.empty')}</ListEmpty>
        )}
      </Card>

      <Card title={t('admin.bills.recharges.title')} className="adm-detail">
        {bill.recharges.length ? (
          <div className="adm-scroll">
            <table className="adm-table adm-stack">
              <thead>
                <tr>
                  <th scope="col">{t('admin.bills.ledger.column.when')}</th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.ledger.column.amount')}
                  </th>
                  <th scope="col">{t('admin.bills.column.status')}</th>
                  <th scope="col">
                    <span className="sr-only">{t('admin.bills.column.actions')}</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {bill.recharges.map(r => (
                  <tr key={r.id}>
                    <td data-label={t('admin.bills.ledger.column.when')}>{when(r.createdAt)}</td>
                    <td className="adm-num" data-label={t('admin.bills.ledger.column.amount')}>
                      {usdOfCents(r.amountCents)}
                    </td>
                    <th scope="row" data-label={t('admin.bills.column.status')}>
                      {t(RECHARGE_STATUS[r.status])}
                      {r.failureCode && <span className="adm-sub adm-mono">{r.failureCode}</span>}
                      {r.invoiceId && stripe(`invoices/${r.invoiceId}`) && (
                        <span className="adm-sub">
                          <a href={stripe(`invoices/${r.invoiceId}`)!} target="_blank" rel="noreferrer">
                            {t('admin.bills.invoices.open')}
                          </a>
                        </span>
                      )}
                    </th>
                    <td>
                      {(r.status === 'failed' || r.status === 'pending') && (
                        <Button
                          size="sm"
                          title={t('admin.bills.recharges.creditTip')}
                          onClick={() => setOpen({ kind: 'credit', rechargeId: r.id, amountCents: r.amountCents })}
                        >
                          {t('admin.bills.recharges.credit')}
                        </Button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <ListEmpty>{t('admin.bills.recharges.empty')}</ListEmpty>
        )}
      </Card>

      <Card title={t('admin.bills.invoices.title')} className="adm-detail">
        {bill.invoices.length ? (
          <div className="adm-scroll">
            <table className="adm-table adm-stack">
              <thead>
                <tr>
                  <th scope="col">{t('admin.bills.invoices.column.invoice')}</th>
                  <th scope="col">{t('admin.bills.column.status')}</th>
                  <th scope="col" className="adm-num">
                    {t('admin.bills.invoices.column.total')}
                  </th>
                  <th scope="col">{t('admin.bills.column.created')}</th>
                </tr>
              </thead>
              <tbody>
                {bill.invoices.map(i => (
                  <tr key={i.invoiceId}>
                    <th scope="row" data-label={t('admin.bills.invoices.column.invoice')}>
                      {stripe(`invoices/${i.invoiceId}`) ? (
                        <a href={stripe(`invoices/${i.invoiceId}`)!} target="_blank" rel="noreferrer">
                          {i.number ?? i.invoiceId}
                        </a>
                      ) : (
                        <span className="adm-mono">{i.number ?? i.invoiceId}</span>
                      )}
                      <span className="adm-sub">{t(INVOICE_KIND[i.kind])}</span>
                    </th>
                    <td data-label={t('admin.bills.column.status')}>{i.status}</td>
                    <td className="adm-num" data-label={t('admin.bills.invoices.column.total')}>
                      {usdOfCents(i.totalCents)}
                      {i.taxCents > 0 && (
                        <span className="adm-sub">
                          {t('admin.bills.invoices.tax', { amount: usdOfCents(i.taxCents) })}
                        </span>
                      )}
                    </td>
                    <td data-label={t('admin.bills.column.created')}>{day(i.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <ListEmpty>{t('admin.bills.invoices.empty')}</ListEmpty>
        )}
      </Card>

      {open && <BillDialog bill={bill} open={open} notify={notify} done={done} onClose={() => setOpen(null)} />}
    </>
  )
}

const RECHARGE_STATUS: Record<AdminBillDetail['recharges'][number]['status'], MessageKey> = {
  pending: msg('admin.bills.recharges.status.pending'),
  paid: msg('admin.bills.recharges.status.paid'),
  failed: msg('admin.bills.recharges.status.failed'),
  canceled: msg('admin.bills.recharges.status.canceled'),
}
const INVOICE_KIND: Record<AdminBillDetail['invoices'][number]['kind'], MessageKey> = {
  subscription: msg('admin.bills.invoices.kind.subscription'),
  recharge: msg('admin.bills.invoices.kind.recharge'),
  topup: msg('admin.bills.invoices.kind.topup'),
}
const CREDIT_KINDS = {
  credit: msg('admin.bills.credit.kind.credit'),
  writeoff: msg('admin.bills.credit.kind.writeoff'),
  adjustment: msg('admin.bills.credit.kind.adjustment'),
} as const satisfies Record<string, MessageKey>
type CreditKind = keyof typeof CREDIT_KINDS
const CREDIT_HELP: Record<CreditKind, MessageKey> = {
  credit: msg('admin.bills.credit.kind.creditHelp'),
  writeoff: msg('admin.bills.credit.kind.writeoffHelp'),
  adjustment: msg('admin.bills.credit.kind.adjustmentHelp'),
}

type DialogProps = {
  bill: AdminBillDetail
  open: Open
  notify: Notify
  /** Reads the bill again and answers the toast. */
  done: (text: string) => Promise<string>
  onClose: () => void
}

/** The dialog of one action on a bill: its own fields, then the reason. */
function BillDialog({ bill, open, notify, done, onClose }: DialogProps) {
  const t = useT()
  const billingAccountId = bill.id
  const [amount, setAmount] = useState(open.kind === 'credit' && open.amountCents ? String(open.amountCents / 100) : '')
  const [creditKind, setCreditKind] = useState<CreditKind>('credit')
  const [count, setCount] = useState(
    open.kind === 'concurrency' && bill.concurrentCallsCap !== null
      ? String(bill.concurrentCallsCap)
      : open.kind === 'cap'
        ? String(bill.rechargeCapBaseCents / 100)
        : '',
  )
  const [member, setMember] = useState(bill.members.find(m => m.id !== bill.owner.id)?.id ?? '')
  const [workspace, setWorkspace] = useState(
    (open.kind === 'attach' ? bill.unbilledWorkspaces[0]?.id : bill.workspaces[0]?.id) ?? '',
  )
  const targets = bill.otherBills.filter(b => b.status !== 'canceled')
  const [target, setTarget] = useState(targets[0]?.id ?? '')
  const [fieldError, setFieldError] = useState<string | null>(null)
  const props = { notify, onClose }

  const amountField = (label: string, aside?: string) => (
    <FormField id="adm-bill-amount" label={label} aside={aside} error={fieldError}>
      <Input
        id="adm-bill-amount"
        inputMode="decimal"
        placeholder={t('admin.bills.amount.placeholder')}
        value={amount}
        invalid={!!fieldError}
        readOnly={open.kind === 'credit' && !!open.rechargeId}
        onChange={e => setAmount(e.target.value)}
      />
    </FormField>
  )

  switch (open.kind) {
    case 'credit': {
      const kind: CreditKind = open.rechargeId ? 'credit' : creditKind
      return (
        <ReasonDialog
          {...props}
          title={t(open.rechargeId ? 'admin.bills.recharges.creditTitle' : 'admin.bills.credit.title')}
          description={t(open.rechargeId ? 'admin.bills.recharges.creditText' : 'admin.bills.credit.text', {
            balance: usdOfMicros(bill.balanceMicros),
          })}
          submit={t('admin.bills.credit.submit')}
          check={() => {
            const parsed = parseDollars(amount, { negative: kind === 'adjustment' })
            setFieldError('problem' in parsed ? parsed.problem : null)
            return 'problem' in parsed ? parsed.problem : null
          }}
          run={async (reason, requestId) => {
            const parsed = parseDollars(amount, { negative: kind === 'adjustment' })
            if ('problem' in parsed) throw new Error(parsed.problem)
            await runAdmin('billing.credit', {
              billingAccountId,
              kind,
              amountCents: parsed.cents,
              reason,
              requestId,
              ...(open.rechargeId ? { rechargeId: open.rechargeId } : {}),
            })
            return done(t('admin.bills.credit.done', { amount: usdOfCents(parsed.cents) }))
          }}
        >
          {!open.rechargeId && (
            <FormField id="adm-bill-kind" label={t('admin.bills.credit.kind.label')}>
              <Select
                id="adm-bill-kind"
                value={creditKind}
                onChange={setCreditKind}
                label={t('admin.bills.credit.kind.label')}
                options={(Object.keys(CREDIT_KINDS) as CreditKind[]).map(value => ({
                  value,
                  label: t(CREDIT_KINDS[value]),
                  description: t(CREDIT_HELP[value]),
                }))}
              />
            </FormField>
          )}
          {amountField(
            t('admin.bills.amount.label'),
            kind === 'adjustment' ? t('admin.bills.amount.negativeAside') : undefined,
          )}
        </ReasonDialog>
      )
    }
    case 'refund': {
      const available = Math.max(0, bill.balanceMicros - bill.reservedMicros)
      const payments = bill.refundable.filter(p => p.creditedMicros > p.refundedMicros)
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.refund.title')}
          description={t('admin.bills.refund.text', { available: usdOfMicros(available) })}
          submit={t('admin.bills.refund.submit')}
          danger
          check={() => {
            const parsed = parseDollars(amount)
            setFieldError('problem' in parsed ? parsed.problem : null)
            return 'problem' in parsed ? parsed.problem : null
          }}
          run={async (reason, requestId) => {
            const parsed = parseDollars(amount)
            if ('problem' in parsed) throw new Error(parsed.problem)
            await runAdmin('billing.refund', { billingAccountId, amountCents: parsed.cents, reason, requestId })
            return done(t('admin.bills.refund.done', { amount: usdOfCents(parsed.cents) }))
          }}
        >
          {payments.length > 0 && (
            <ul className="adm-refundable">
              {payments.map(p => (
                <li key={p.entryId}>
                  {t('admin.bills.refund.payment', {
                    when: day(p.createdAt),
                    paid: usdOfMicros(p.creditedMicros),
                    left: usdOfMicros(p.creditedMicros - p.refundedMicros),
                  })}
                </li>
              ))}
            </ul>
          )}
          {amountField(t('admin.bills.amount.label'))}
        </ReasonDialog>
      )
    }
    case 'status': {
      const keys = {
        comped: [
          msg('admin.bills.status.compTitle'),
          msg('admin.bills.status.compText'),
          msg('admin.bills.status.compDone'),
        ],
        suspended: [
          msg('admin.bills.status.suspendTitle'),
          msg('admin.bills.status.suspendText'),
          msg('admin.bills.status.suspendDone'),
        ],
        active: [
          msg('admin.bills.status.resumeTitle'),
          msg('admin.bills.status.resumeText'),
          msg('admin.bills.status.resumeDone'),
        ],
      } as const
      const [title, text, doneKey] = keys[open.status]
      return (
        <ReasonDialog
          {...props}
          title={t(title)}
          description={t(text)}
          submit={t(title)}
          danger={open.status === 'suspended'}
          run={async reason => {
            await runAdmin('billing.adminSetStatus', { billingAccountId, status: open.status, reason })
            return done(t(doneKey))
          }}
        />
      )
    }
    case 'cap':
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.cap.title')}
          description={t('admin.bills.cap.text', { cap: usdOfCents(bill.rechargeCapCents) })}
          submit={t('common.action.save')}
          check={() => {
            const parsed = parseDollars(count, { zero: true })
            setFieldError('problem' in parsed ? parsed.problem : null)
            return 'problem' in parsed ? parsed.problem : null
          }}
          run={async reason => {
            const parsed = parseDollars(count, { zero: true })
            if ('problem' in parsed) throw new Error(parsed.problem)
            await runAdmin('billing.setCap', { billingAccountId, capBaseCents: parsed.cents, reason })
            return done(t('admin.bills.cap.done', { amount: usdOfCents(parsed.cents) }))
          }}
        >
          <FormField id="adm-bill-cap" label={t('admin.bills.cap.label')} error={fieldError}>
            <Input
              id="adm-bill-cap"
              inputMode="decimal"
              value={count}
              invalid={!!fieldError}
              onChange={e => setCount(e.target.value)}
            />
          </FormField>
        </ReasonDialog>
      )
    case 'concurrency':
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.concurrency.title')}
          description={t('admin.bills.concurrency.text', { count: bill.rulesConcurrentCalls })}
          submit={t('common.action.save')}
          check={() => {
            const parsed = parseCount(count, 1, 1000, { empty: true })
            setFieldError('problem' in parsed ? parsed.problem : null)
            return 'problem' in parsed ? parsed.problem : null
          }}
          run={async reason => {
            const parsed = parseCount(count, 1, 1000, { empty: true })
            if ('problem' in parsed) throw new Error(parsed.problem)
            await runAdmin('billing.setConcurrency', { billingAccountId, concurrentCalls: parsed.value, reason })
            return done(
              parsed.value === null
                ? t('admin.bills.concurrency.reset')
                : t('admin.bills.concurrency.done', { count: parsed.value }),
            )
          }}
        >
          <FormField
            id="adm-bill-calls"
            label={t('admin.bills.concurrency.label')}
            aside={t('admin.bills.concurrency.aside')}
            error={fieldError}
          >
            <Input
              id="adm-bill-calls"
              inputMode="numeric"
              value={count}
              invalid={!!fieldError}
              onChange={e => setCount(e.target.value)}
            />
          </FormField>
        </ReasonDialog>
      )
    case 'owner':
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.owner.title')}
          description={t('admin.bills.owner.text')}
          submit={t('admin.bills.owner.submit')}
          check={() => (member ? null : t('admin.bills.owner.pick'))}
          run={async reason => {
            await runAdmin('billing.transferOwner', { billingAccountId, userId: member, reason })
            const to = bill.members.find(m => m.id === member)
            return done(t('admin.bills.owner.done', { owner: to?.email ?? member }))
          }}
        >
          <FormField id="adm-bill-owner" label={t('admin.bills.owner.label')}>
            <Select
              id="adm-bill-owner"
              value={member}
              onChange={setMember}
              label={t('admin.bills.owner.label')}
              options={bill.members.map(m => ({
                value: m.id,
                label: m.name ? `${m.name} (${m.email})` : m.email,
                disabled: m.id === bill.owner.id,
                description: m.id === bill.owner.id ? t('admin.bills.owner.current') : undefined,
              }))}
            />
          </FormField>
        </ReasonDialog>
      )
    case 'move':
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.move.title')}
          description={t('admin.bills.move.text')}
          submit={t('admin.bills.move.submit')}
          check={() => (workspace && target ? null : t('admin.bills.move.pick'))}
          run={async (reason, requestId) => {
            await runAdmin('billing.moveWorkspace', {
              workspaceId: workspace,
              toBillingAccountId: target,
              reason,
              requestId,
            })
            await refreshQuery(billKey(target))
            const name = bill.workspaces.find(w => w.id === workspace)?.name ?? ''
            return done(t('admin.bills.move.done', { name }))
          }}
        >
          <FormField id="adm-bill-workspace" label={t('admin.bills.move.workspace')}>
            <Select
              id="adm-bill-workspace"
              value={workspace}
              onChange={setWorkspace}
              label={t('admin.bills.move.workspace')}
              options={bill.workspaces.map(w => ({ value: w.id, label: w.name }))}
            />
          </FormField>
          <FormField id="adm-bill-target" label={t('admin.bills.move.target')}>
            <Select
              id="adm-bill-target"
              value={target}
              onChange={setTarget}
              label={t('admin.bills.move.target')}
              options={targets.map(b => ({
                value: b.id,
                label: b.owner ?? b.id,
                description: `${t(b.kind === 'partner' ? 'admin.bills.kind.partner' : 'admin.bills.kind.cloud')} · ${t(STATUS[b.status])}`,
              }))}
            />
          </FormField>
        </ReasonDialog>
      )
    case 'attach':
      return (
        <ReasonDialog
          {...props}
          title={t('admin.bills.attach.title')}
          description={t('admin.bills.attach.text')}
          submit={t('admin.bills.attach.submit')}
          check={() => (workspace ? null : t('admin.bills.attach.pick'))}
          run={async (reason, requestId) => {
            await runAdmin('billing.moveWorkspace', {
              workspaceId: workspace,
              toBillingAccountId: billingAccountId,
              reason,
              requestId,
            })
            const name = bill.unbilledWorkspaces.find(w => w.id === workspace)?.name ?? ''
            return done(t('admin.bills.attach.done', { name }))
          }}
        >
          <FormField id="adm-bill-unbilled" label={t('admin.bills.move.workspace')}>
            <Select
              id="adm-bill-unbilled"
              value={workspace}
              onChange={setWorkspace}
              label={t('admin.bills.move.workspace')}
              options={bill.unbilledWorkspaces.map(w => ({ value: w.id, label: w.name }))}
            />
          </FormField>
        </ReasonDialog>
      )
  }
}

type ReasonDialogProps = {
  title: string
  description?: ReactNode
  submit: string
  /** A step that takes something away (suspend, deny, refund): its button is red. */
  danger?: boolean
  /** The other fields' problem, if any; shown by the field itself. */
  check?: () => string | null
  /** Does it; answers the toast. `requestId`: the same for every try in this dialog. */
  run: (reason: string, requestId: string) => Promise<string>
  notify: Notify
  onClose: () => void
  children?: ReactNode
}

/** Every billing write asks why: the reason is kept in the audit log with the action. */
function ReasonDialog({
  title,
  description,
  submit,
  danger,
  check,
  run,
  notify,
  onClose,
  children,
}: ReasonDialogProps) {
  const t = useT()
  const [reason, setReason] = useState('')
  const [reasonError, setReasonError] = useState<string | null>(null)
  const [problem, setProblem] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  // One per dialog, so a retry after an error or a lost answer is the same request (Stripe's idempotency key).
  const [requestId] = useState(newRequestId)

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    const fieldProblem = check?.() ?? null
    const why = reasonProblem(reason)
    setReasonError(why)
    if (fieldProblem || why) return
    setProblem(null)
    setBusy(true)
    try {
      const text = await run(reason.trim(), requestId)
      onClose()
      notify(text)
    } catch (err) {
      setProblem(errorText(err))
    } finally {
      setBusy(false)
    }
  }
  return (
    <Dialog
      title={title}
      description={description}
      onClose={onClose}
      onSubmit={e => void onSubmit(e)}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>
            {t('common.action.cancel')}
          </Button>
          <Button type="submit" variant={danger ? 'danger' : 'primary'} busy={busy}>
            {submit}
          </Button>
        </>
      }
    >
      {children}
      <FormField
        id="adm-bill-reason"
        label={t('admin.bills.reason.label')}
        aside={t('admin.bills.reason.aside')}
        error={reasonError}
      >
        <Textarea
          id="adm-bill-reason"
          rows={2}
          value={reason}
          invalid={!!reasonError}
          placeholder={t('admin.bills.reason.placeholder')}
          onChange={e => setReason(e.target.value)}
        />
      </FormField>
      {problem && <FormMessage>{problem}</FormMessage>}
    </Dialog>
  )
}