"use client";

import * as React from "react";
import { useQuery } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { MessageSquare, Hash, Clock, Gauge, BarChart3, Loader2 } from "lucide-react";

interface StatsResponse {
  totals: {
    chats: number;
    messages: number;
    userMessages: number;
    assistantMessages: number;
    promptTokens: number;
    completionTokens: number;
    totalEvalSeconds: number;
    totalDurationSeconds: number;
    avgTokensPerSecond: number;
  };
  perModel: Array<{
    model: string;
    messages: number;
    promptTokens: number;
    completionTokens: number;
    totalEvalSeconds: number;
    totalDurationSeconds: number;
    avgTokensPerSecond: number;
  }>;
}

function formatSeconds(s: number): string {
  if (s < 60) return `${s.toFixed(1)}s`;
  if (s < 3600) return `${Math.floor(s / 60)}m ${Math.round(s % 60)}s`;
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  return `${h}h ${m}m`;
}

export function StatsSettings() {
  const statsQuery = useQuery({
    queryKey: ["stats"],
    queryFn: () => apiFetch<StatsResponse>("/api/stats"),
  });

  if (statsQuery.isLoading) {
    return (
      <div className="flex items-center gap-2 p-4 text-sm text-muted-foreground">
        <Loader2 className="h-4 w-4 animate-spin" />
        Loading stats…
      </div>
    );
  }
  if (statsQuery.isError || !statsQuery.data) {
    return (
      <div className="p-4 text-sm text-destructive">
        Failed to load stats.
      </div>
    );
  }

  const { totals, perModel } = statsQuery.data;
  const hasData = totals.assistantMessages > 0;

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>Usage overview</CardTitle>
          <CardDescription>
            Aggregated across all your chats. Updates after each message.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {!hasData ? (
            <p className="text-sm text-muted-foreground">
              No assistant messages yet — send something to start tracking stats.
            </p>
          ) : (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
              <Stat
                icon={<MessageSquare className="h-3.5 w-3.5" />}
                label="Chats"
                value={totals.chats.toLocaleString()}
              />
              <Stat
                icon={<MessageSquare className="h-3.5 w-3.5" />}
                label="Messages"
                value={totals.messages.toLocaleString()}
                sub={`${totals.userMessages} you · ${totals.assistantMessages} AI`}
              />
              <Stat
                icon={<Hash className="h-3.5 w-3.5" />}
                label="Tokens in"
                value={totals.promptTokens.toLocaleString()}
              />
              <Stat
                icon={<Hash className="h-3.5 w-3.5" />}
                label="Tokens out"
                value={totals.completionTokens.toLocaleString()}
              />
              <Stat
                icon={<Clock className="h-3.5 w-3.5" />}
                label="Generation time"
                value={formatSeconds(totals.totalEvalSeconds)}
              />
              <Stat
                icon={<Clock className="h-3.5 w-3.5" />}
                label="Total time"
                value={formatSeconds(totals.totalDurationSeconds)}
              />
              <Stat
                icon={<Gauge className="h-3.5 w-3.5" />}
                label="Avg tok/s"
                value={`${totals.avgTokensPerSecond} tok/s`}
              />
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <BarChart3 className="h-4 w-4" />
            Per model
          </CardTitle>
          <CardDescription>Breakdown by model used.</CardDescription>
        </CardHeader>
        <CardContent>
          {perModel.length === 0 ? (
            <p className="text-sm text-muted-foreground">No model data yet.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs font-medium text-muted-foreground">
                    <th className="py-2 pr-4">Model</th>
                    <th className="py-2 pr-4 text-right">Msgs</th>
                    <th className="py-2 pr-4 text-right">In</th>
                    <th className="py-2 pr-4 text-right">Out</th>
                    <th className="py-2 pr-4 text-right">Gen time</th>
                    <th className="py-2 pr-0 text-right">Avg tok/s</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {perModel.map((m) => (
                    <tr key={m.model}>
                      <td className="py-2 pr-4 font-mono text-xs">{m.model}</td>
                      <td className="py-2 pr-4 text-right tabular-nums">{m.messages}</td>
                      <td className="py-2 pr-4 text-right tabular-nums">
                        {m.promptTokens.toLocaleString()}
                      </td>
                      <td className="py-2 pr-4 text-right tabular-nums">
                        {m.completionTokens.toLocaleString()}
                      </td>
                      <td className="py-2 pr-4 text-right tabular-nums">
                        {formatSeconds(m.totalEvalSeconds)}
                      </td>
                      <td className="py-2 pr-0 text-right tabular-nums font-medium">
                        {m.avgTokensPerSecond}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function Stat({
  icon,
  label,
  value,
  sub,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  sub?: string;
}) {
  return (
    <div className="rounded-xl border border-border bg-card/50 p-3">
      <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-muted-foreground">
        {icon}
        {label}
      </div>
      <div className="mt-1.5 font-serif text-xl tabular-nums">{value}</div>
      {sub && <div className="mt-0.5 text-[11px] text-muted-foreground">{sub}</div>}
    </div>
  );
}
