import Link from "next/link";

import { cn } from "@/lib/utils";

/** One line of a money card: what the balance is, the amount, an optional status line and the records behind it. */
export type MoneyLine = { label: string; value: string; note?: string; href?: string; negative?: boolean };

/**
 * Money card (02-data-display §5, DB-07, DB-13): balances grouped by section (Owed to us / We owe, Tax, Stock, Costs;
 * Cash & bank per branch), each figure beside its words. "As at" sits once in the header. `chart` (card 040) draws
 * the balances above the groups inside the same card: the ageing chart for Money summary, the branch money chart for
 * Cash and bank.
 */
export function MoneyCard({ title, asAt, groups, footer, chart }: { title: string; asAt?: string; groups: { name: string; rows: MoneyLine[] }[]; footer?: React.ReactNode; chart?: React.ReactNode }) {
  return (
    <div className="h-full rounded-lg border border-border bg-card p-3">
      <div className="flex items-baseline justify-between gap-2">
        <p className="text-xs font-medium text-muted-foreground">{title}</p>
        {asAt ? <span className="text-xs text-muted-foreground">As at {asAt}</span> : null}
      </div>
      {chart ? <div className="mt-2">{chart}</div> : null}
      <div className="mt-3 grid gap-3 sm:grid-cols-2">
        {groups.map((g) => (
          <section key={g.name} aria-label={g.name}>
            <h4 className="text-[11px] font-semibold tracking-wide text-muted-foreground uppercase">{g.name}</h4>
            <dl className="mt-1 space-y-1 text-sm">
              {g.rows.map((r) => (
                <div key={r.label} className="flex items-baseline justify-between gap-3">
                  <dt className="text-muted-foreground">{r.href ? <Link href={r.href} className="text-primary hover:underline">{r.label}</Link> : r.label}</dt>
                  <dd className={cn("font-medium tabular-nums", (r.negative || r.note) && "text-status-error-text")}>
                    {r.value}
                    {r.note ? <span className="block text-right text-[11px] font-normal">{r.note}</span> : null}
                  </dd>
                </div>
              ))}
            </dl>
          </section>
        ))}
      </div>
      {footer}
    </div>
  );
}
