import type { Stats } from '../api';

interface Props {
  stats: Stats | null;
  loading: boolean;
  error: string | null;
}

export function StatsCards({ stats, loading, error }: Props) {
  if (loading) return <CardGrid values={[]} />;
  if (error) return <p className="text-danger text-sm">Failed to load stats</p>;
  if (!stats) return null;

  const cards = [
    { label: 'Sessions', value: stats.total_sessions },
    { label: 'Messages', value: stats.total_messages },
    { label: 'Input tokens', value: fmt(stats.tokens.input) },
    { label: 'Output tokens', value: fmt(stats.tokens.output) },
    { label: 'Cached tokens', value: fmt(stats.tokens.cached) },
    { label: 'Thinking tokens', value: fmt(stats.tokens.thinking) },
  ];

  return <CardGrid values={cards} />;
}

function CardGrid({ values }: { values: { label: string; value: string | number }[] }) {
  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
      {values.map((c) => (
        <div
          key={c.label}
          className="bg-surface-raised border border-border rounded-lg px-4 py-3"
        >
          <p className="text-xs text-text-muted uppercase tracking-wide">{c.label}</p>
          <p className="text-2xl font-semibold text-text-primary mt-1">{c.value}</p>
        </div>
      ))}
    </div>
  );
}

function fmt(n: number): string {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';
  if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
  return String(n);
}
