"use client";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { AgingBuckets, BalanceSummary, PaymentForm, StatementTable, StatTile } from "@/components/medora/records/finance";
import { RecordStatusBadge, RoleBadge, STATUS_MAP, type StatusDomain, type StatusLabel } from "@/components/medora/records/status";
import { customers, kpis, salesByDay, suppliers, TODAY } from "@/lib/mock-data";

const DOMAIN_LABEL: Record<StatusDomain, string> = {
  sale: "Sale",
  stock: "Stock",
  prescription: "Prescription",
  purchaseOrder: "Purchase order",
  shift: "Shift",
  user: "User",
};

const owing = customers.find((c) => c.balance > 0 && c.creditLimit > 0) ?? customers[1];
const trend = salesByDay.slice(-14).map((d) => d.revenue);

export function FinanceSection() {
  return (
    <Section
      id="status-and-finance"
      title="Status and money"
      description="Every status in the product comes from one typed map, so a label can only be used in its own domain. Money is right-aligned with tabular figures."
    >
      <Example title="Status badge system" description="STATUS_MAP: domain, label, tone" code={`<RecordStatusBadge domain="sale" status="Paid" />`} bare>
        <table className="w-full text-sm">
          <tbody>
            {(Object.keys(STATUS_MAP) as StatusDomain[]).map((d) => (
              <tr key={d} className="border-b border-border last:border-b-0">
                <th scope="row" className="w-40 px-4 py-2 text-left text-xs font-normal text-muted-foreground">
                  {DOMAIN_LABEL[d]}
                </th>
                <td className="flex flex-wrap gap-2 px-4 py-2">
                  {(Object.keys(STATUS_MAP[d]) as StatusLabel<typeof d>[]).map((s) => (
                    <RecordStatusBadge key={s} domain={d} status={s as never} />
                  ))}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Example>

      <Example title="Role badge" description="Identity, so teal, blue and grey rather than status colours" className="flex gap-2">
        <RoleBadge role="Admin" />
        <RoleBadge role="Pharmacist" />
        <RoleBadge role="Cashier" />
      </Example>

      <Example title="Stat tile" description="Default, falling-is-good, no trend, loading, error" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <StatTile label="Today's sales" value={`KES ${kpis.todayRevenue.toLocaleString("en-US")}`} delta={kpis.todayChange * 100} hint="vs yesterday" trend={trend} />
        <StatTile label="Overdue receivables" value="KES 48,300" delta={-6.2} deltaGoodWhen="down" hint="vs last week" trend={[9, 8, 8, 7, 7, 6, 6, 5]} />
        <StatTile label="Transactions" value={String(kpis.todayTransactions)} hint="No comparison available" />
        <StatTile label="Gross profit" value="" loading />
        <StatTile label="Stock value" value="" error="Could not load stock value. Try again." />
      </Example>

      <Example title="Balance summary" description="Receivable and payable, within limit, near limit, over limit, no limit, loading" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <BalanceSummary kind="receivable" balance={4200} creditLimit={20000} />
        <BalanceSummary kind="receivable" balance={owing.creditLimit * 0.85} creditLimit={owing.creditLimit} overdue={1800} />
        <BalanceSummary kind="receivable" balance={11500} creditLimit={10000} overdue={11500} />
        <BalanceSummary kind="payable" balance={suppliers[0].balanceOwed} />
        <BalanceSummary kind="payable" balance={0} loading />
      </Example>

      <Example title="Aging buckets" description="Normal, and loading" className="space-y-3">
        <AgingBuckets data={{ current: 18400, d31to60: 9200, d61to90: 4100, over90: 2600 }} />
        <AgingBuckets data={{ current: 0, d31to60: 0, d61to90: 0, over90: 0 }} loading />
      </Example>

      <Example title="Statement table" description="Opening balance, invoices, receipts, running balance" bare>
        <StatementTable
          openingBalance={3200}
          rows={[
            { date: "2026-09-28", ref: "RCP-005012", description: "Sale on account", charge: 2450 },
            { date: "2026-10-02", ref: "PAY-0101", description: "Receipt, M-Pesa", payment: 3200 },
            { date: "2026-10-09", ref: "RCP-005088", description: "Sale on account", charge: 1980 },
            { date: "2026-10-15", ref: "RCP-005141", description: "Sale on account", charge: 860 },
            { date: "2026-10-18", ref: "PAY-0107", description: "Receipt, Cash", payment: 1000 },
          ]}
        />
      </Example>

      <Example title="Payment recording form" description="Idle, submitting, error, disabled" className="grid gap-4 lg:grid-cols-2">
        <PaymentForm party={owing.name} outstanding={owing.balance || 4200} today={TODAY} />
        <PaymentForm party={owing.name} outstanding={owing.balance || 4200} today={TODAY} status="submitting" />
        <PaymentForm party={owing.name} outstanding={owing.balance || 4200} today={TODAY} status="error" error="The payment could not be saved. Check the connection and try again." />
        <PaymentForm party={owing.name} outstanding={0} today={TODAY} status="disabled" />
      </Example>
    </Section>
  );
}
