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 <div className="text-text-muted text-sm">Loading...</div>;
  if (error) return <p className="text-danger text-sm">Failed to load stats</p>;
  if (!stats) return null;

  const totalTokens = stats.tokens.input + stats.tokens.output + stats.tokens.cached + stats.tokens.thinking;

  return (
    <div className="space-y-4">
      {/* Top-level numbers */}
      <div className="grid grid-cols-3 gap-4">
        <Card label="Sessions" value={stats.total_sessions} />
        <Card label="Messages" value={stats.total_messages} />
        <Card label="Total Tokens" value={fmt(totalTokens)} />
      </div>

      {/* Org breakdown */}
      {stats.by_org && stats.by_org.length > 0 && (
        <div className="bg-surface-raised border border-border rounded-lg px-4 py-3">
          <p className="text-xs text-text-muted uppercase tracking-wide mb-2">By Organization</p>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
            {stats.by_org.map((o) => (
              <div key={o.org} className="space-y-0.5">
                <p className="text-sm font-medium text-text-primary">{o.org}</p>
                <p className="text-xs text-text-muted tabular-nums">
                  {fmt(o.session_count)} sessions · {fmt(o.message_count)} msgs
                </p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Source breakdown + Token breakdown side by side */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {stats.by_source.length > 0 && (
          <div className="bg-surface-raised border border-border rounded-lg px-4 py-3">
            <p className="text-xs text-text-muted uppercase tracking-wide mb-2">Messages by Source</p>
            <div className="space-y-1.5">
              {stats.by_source.map((s) => (
                <div key={s.source} className="flex items-center justify-between text-sm">
                  <span className="text-text-secondary">{s.source.replaceAll('_', ' ')}</span>
                  <span className="text-text-primary font-medium tabular-nums">
                    {fmt(s.count)}{' '}
                    <span className="text-text-muted text-xs">
                      ({pct(s.count, stats.total_messages)})
                    </span>
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        {totalTokens > 0 && (
          <div className="bg-surface-raised border border-border rounded-lg px-4 py-3">
            <p className="text-xs text-text-muted uppercase tracking-wide mb-2">Token Breakdown</p>
            <div className="space-y-1.5">
              {([
                ['Input', stats.tokens.input],
                ['Output', stats.tokens.output],
                ['Cached', stats.tokens.cached],
                ['Thinking', stats.tokens.thinking],
              ] as const).filter(([, v]) => v > 0).map(([label, value]) => (
                <div key={label} className="flex items-center justify-between text-sm">
                  <span className="text-text-secondary">{label}</span>
                  <span className="text-text-primary font-medium tabular-nums">
                    {fmt(value)}{' '}
                    <span className="text-text-muted text-xs">
                      ({pct(value, totalTokens)})
                    </span>
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Card({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="bg-surface-raised border border-border rounded-lg px-4 py-3">
      <p className="text-xs text-text-muted uppercase tracking-wide">{label}</p>
      <p className="text-2xl font-semibold text-text-primary mt-1">{value}</p>
    </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);
}

function pct(n: number, total: number): string {
  if (total === 0) return '0%';
  return ((n / total) * 100).toFixed(1) + '%';
}
