import useSWR from 'swr';
import { api, type AnalyticsSummary, type TimeseriesPoint, type ModelBreakdown } from '../lib/api';
import CostChart from '../components/CostChart';
import StatCard from '../components/StatCard';
import ModelTable from '../components/ModelTable';

export default function Dashboard() {
  const { data: summary } = useSWR('summary', api.getSummary);
  const { data: timeseries } = useSWR('timeseries', () => api.getTimeseries('hour'));
  const { data: models } = useSWR('models', api.getModels);

  return (
    <div className="space-y-6">
      <h2 className="text-xl font-semibold">Dashboard</h2>

      {/* Stat cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          label="Total Requests"
          value={summary?.total_requests?.toLocaleString() ?? '—'}
          sub="Last 7 days"
        />
        <StatCard
          label="Cost Saved"
          value={summary ? `$${summary.total_cost_saved.toFixed(2)}` : '—'}
          sub={summary ? `${summary.savings_pct.toFixed(1)}% savings` : ''}
          accent="success"
        />
        <StatCard
          label="Avg Latency"
          value={summary ? `${summary.avg_latency_ms}ms` : '—'}
          sub={summary ? `P99: ${summary.p99_latency_ms}ms` : ''}
        />
        <StatCard
          label="Routed"
          value={summary ? `${((summary.routing_decisions.cheapest / Math.max(summary.total_requests, 1)) * 100).toFixed(0)}%` : '—'}
          sub="Requests downgraded"
          accent="primary"
        />
      </div>

      {/* Cost savings chart */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg p-4">
        <h3 className="text-sm font-medium text-dd0c-muted mb-4">Cost Savings Over Time</h3>
        <CostChart data={timeseries ?? []} />
      </div>

      {/* Model breakdown */}
      <div className="bg-dd0c-surface border border-dd0c-border rounded-lg p-4">
        <h3 className="text-sm font-medium text-dd0c-muted mb-4">Model Usage</h3>
        <ModelTable data={models ?? []} />
      </div>
    </div>
  );
}
