import { formatMicros } from "@/lib/format";
import type { StatsTotals } from "@/lib/types";

const numberFormat = new Intl.NumberFormat();

function percentOf(part: number, total: number): string | null {
	if (total === 0) return null;
	return `${((part / total) * 100).toFixed(1)}%`;
}

function Card({ label, value, detail }: { label: string; value: string; detail?: string | null }) {
	return (
		<div className="rounded border border-zinc-200 bg-white px-4 py-3 dark:border-zinc-800 dark:bg-zinc-900">
			<dt className="text-sm text-zinc-500">{label}</dt>
			<dd>
				<span className="text-2xl font-semibold tabular-nums">{value}</span>
				{detail != null && <span className="ml-2 text-sm text-zinc-500 tabular-nums">{detail}</span>}
			</dd>
		</div>
	);
}

export default function StatCards({ stats }: { stats: StatsTotals }) {
	return (
		<dl className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">
			<Card label="Queries" value={numberFormat.format(stats.queries)} />
			<Card
				label="Blocked"
				value={numberFormat.format(stats.blocked)}
				detail={percentOf(stats.blocked, stats.queries)}
			/>
			<Card
				label="Cached"
				value={numberFormat.format(stats.cached)}
				detail={percentOf(stats.cached, stats.queries)}
			/>
			<Card label="Clients" value={numberFormat.format(stats.clients)} />
			<Card
				label="Avg response"
				value={stats.avg_response_time_us === null ? "—" : formatMicros(stats.avg_response_time_us)}
			/>
		</dl>
	);
}
