import { requireUser } from "@/lib/auth";
import { listRecords, accountsWithBalance } from "@/lib/records";
import { RESOURCES } from "@/lib/resources";
import { MHead, MTabs } from "./MotherShell";
import { ResourceView } from "./ResourceView";

export type Stat = [label: string, value: string, sub?: string];
export const Stats = ({ items }: { items: Stat[] }) => (
  <div className="mb-5 grid grid-cols-2 gap-3 xl:grid-cols-4">{items.map(([k, v, s]) => <div key={k} className="m-card m-stat"><div className="k">{k}</div><div className="v">{v}</div>{s && <div className="s">{s}</div>}</div>)}</div>);
export const taka = (n: number) => "৳" + (Math.round(n * 100) / 100).toLocaleString("en-US");

export async function RecordPage({ resource, title, sub, tabs, stats, printHref, children }: { resource: string; title?: string; sub?: string; tabs?: { href: string; label: string }[]; stats?: (rows: any[]) => Stat[]; printHref?: string; children?: React.ReactNode }) {
  await requireUser(["admin"]);
  const def = RESOURCES[resource]; const rows = resource === "accounts" ? accountsWithBalance() : listRecords(resource);
  return (<><MHead title={title || def.title} sub={sub || def.desc} />{tabs && <MTabs tabs={tabs} />}{stats && <Stats items={stats(rows)} />}{children}<ResourceView resource={resource} rows={rows} printHref={printHref} /></>);
}
