import * as stylex from "@stylexjs/stylex";
import { formatMicros } from "@/lib/format";
import type { StatsTotals } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";

const numberFormat = new Intl.NumberFormat();

const styles = stylex.create({
	/** Two columns on a phone, three from `md`, five from `xl`, as before. */
	grid: {
		display: "grid",
		gap: "0.75rem",
		gridTemplateColumns: {
			default: "repeat(2, minmax(0, 1fr))",
			"@media (min-width: 768px)": "repeat(3, minmax(0, 1fr))",
			"@media (min-width: 1280px)": "repeat(5, minmax(0, 1fr))",
		},
	},
	card: {
		borderRadius: "0.25rem",
		borderWidth: 1,
		borderStyle: "solid",
		borderColor: colors.border,
		backgroundColor: colors.surfaceRaised,
		paddingInline: "1rem",
		paddingBlock: "0.75rem",
	},
	label: {
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.textMuted,
	},
	value: {
		fontSize: "1.5rem",
		lineHeight: "2rem",
		fontWeight: 600,
	},
	detail: {
		marginLeft: "0.5rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.textMuted,
	},
});

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 {...stylex.props(styles.card)}>
			<dt {...stylex.props(styles.label)}>{label}</dt>
			<dd>
				<span {...stylex.props(styles.value, shared.tabularNums)}>{value}</span>
				{detail != null && <span {...stylex.props(styles.detail, shared.tabularNums)}>{detail}</span>}
			</dd>
		</div>
	);
}

export default function StatCards({ stats }: { stats: StatsTotals }) {
	return (
		<dl {...stylex.props(styles.grid)}>
			<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>
	);
}
