"use client";

import { useState, useEffect } from "react";
import { Cpu, Search, Database, AlertCircle, TrendingUp } from "lucide-react";

interface AtlasEntry {
  id: string;
  gpuModel: string;
  vramMb: number;
  modelId: string;
  quantization: string;
  tpsP50: number;
  tpsP10: number;
  successRate: number;
  measurementCount: number;
  firstTokenLatencyMs: number;
  updatedAt: string;
}

function SkeletonRow() {
  return (
    <tr className="border-b border-white/5">
      {Array.from({ length: 8 }).map((_, i) => (
        <td key={i} className="px-4 py-3">
          <div className="h-4 rounded bg-white/[0.06] animate-pulse" style={{ width: `${60 + (i * 13) % 40}%` }} />
        </td>
      ))}
    </tr>
  );
}

function SuccessBadge({ rate }: { rate: number }) {
  const pct = Math.round(rate * 100);
  const color =
    pct >= 95 ? "text-emerald-400 bg-emerald-400/10" :
    pct >= 80 ? "text-amber-400 bg-amber-400/10" :
    "text-red-400 bg-red-400/10";
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${color}`}>
      {pct}%
    </span>
  );
}

export default function PerformancePageClient() {
  const [entries, setEntries] = useState<AtlasEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [gpuFilter, setGpuFilter] = useState("");
  const [debouncedGpu, setDebouncedGpu] = useState("");

  // Debounce GPU filter input
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedGpu(gpuFilter), 300);
    return () => clearTimeout(timer);
  }, [gpuFilter]);

  useEffect(() => {
    async function fetchAtlas() {
      setLoading(true);
      setError(null);
      try {
        const params = new URLSearchParams();
        if (debouncedGpu) params.set("gpu", debouncedGpu);
        const res = await fetch(`/api/atlas?${params.toString()}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data: AtlasEntry[] = await res.json();
        setEntries(data);
      } catch {
        setError("Failed to load atlas data. Please try again.");
      } finally {
        setLoading(false);
      }
    }

    fetchAtlas();
  }, [debouncedGpu]);

  const totalMeasurements = entries.reduce((sum, e) => sum + e.measurementCount, 0);

  return (
    <div className="min-h-screen bg-[#0a0a0f] text-white">
      {/* Hero */}
      <div className="border-b border-white/[0.06] bg-gradient-to-b from-violet-950/20 to-transparent">
        <div className="mx-auto max-w-7xl px-4 py-16 sm:px-6 lg:px-8">
          <div className="flex items-center gap-3 mb-4">
            <div className="rounded-xl bg-violet-500/10 p-2.5 border border-violet-500/20">
              <Cpu className="h-6 w-6 text-violet-400" />
            </div>
            <span className="text-sm font-medium text-violet-400 uppercase tracking-widest">
              Performance Atlas
            </span>
          </div>
          <h1 className="text-4xl font-bold tracking-tight text-white sm:text-5xl mb-4">
            GPU Performance Atlas
          </h1>
          <p className="text-lg text-slate-400 max-w-2xl mb-6">
            Real-world LLM performance data crowdsourced from the LLMHosts fleet.
            Tokens/sec, VRAM usage, and success rates for every GPU x model combination.
          </p>

          {/* Stats */}
          <div className="flex flex-wrap gap-6">
            <div className="flex items-center gap-2 text-sm">
              <Database className="h-4 w-4 text-slate-500" />
              <span className="text-slate-400">
                {loading ? (
                  <span className="inline-block h-4 w-20 rounded bg-white/[0.06] animate-pulse" />
                ) : (
                  <>
                    <span className="text-white font-semibold">
                      {totalMeasurements.toLocaleString()}
                    </span>{" "}
                    measurements
                  </>
                )}
              </span>
            </div>
            <div className="flex items-center gap-2 text-sm">
              <TrendingUp className="h-4 w-4 text-slate-500" />
              <span className="text-slate-400">
                {loading ? (
                  <span className="inline-block h-4 w-16 rounded bg-white/[0.06] animate-pulse" />
                ) : (
                  <>
                    <span className="text-white font-semibold">{entries.length}</span> GPU x model
                    pairs
                  </>
                )}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
        {/* Search bar */}
        <div className="mb-6 flex items-center gap-3">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500 pointer-events-none" />
            <input
              type="text"
              placeholder="Filter by GPU model..."
              value={gpuFilter}
              onChange={(e) => setGpuFilter(e.target.value)}
              className="w-full rounded-lg border border-white/10 bg-white/[0.04] py-2.5 pl-9 pr-4 text-sm text-white placeholder-slate-500 focus:border-violet-500/50 focus:outline-none focus:ring-1 focus:ring-violet-500/30 transition-colors"
            />
          </div>
          {gpuFilter && (
            <button
              onClick={() => setGpuFilter("")}
              className="text-xs text-slate-400 hover:text-white transition-colors"
            >
              Clear
            </button>
          )}
        </div>

        {/* Error state */}
        {error && (
          <div className="flex items-center gap-3 rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400 mb-6">
            <AlertCircle className="h-4 w-4 shrink-0" />
            {error}
          </div>
        )}

        {/* Table */}
        <div className="rounded-xl border border-white/[0.08] bg-white/[0.02] overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/[0.08] bg-white/[0.03]">
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                    GPU Model
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                    VRAM
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                    Model
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                    Quant
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                    Tokens/sec
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                    Latency
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                    Success
                  </th>
                  <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                    Samples
                  </th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  Array.from({ length: 8 }).map((_, i) => <SkeletonRow key={i} />)
                ) : entries.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="px-4 py-16 text-center">
                      <div className="flex flex-col items-center gap-3 text-slate-500">
                        <Database className="h-10 w-10 opacity-30" />
                        <p className="text-base font-medium text-slate-400">No data yet</p>
                        <p className="text-sm">
                          Be the first to contribute by running LLMHosts on your GPU
                        </p>
                        <code className="mt-2 rounded bg-white/[0.05] px-3 py-1.5 text-xs text-violet-400 border border-white/10">
                          pip install llmhosts &amp;&amp; llmhosts up
                        </code>
                      </div>
                    </td>
                  </tr>
                ) : (
                  entries.map((entry) => (
                    <tr
                      key={entry.id}
                      className="border-b border-white/[0.04] hover:bg-white/[0.02] transition-colors"
                    >
                      <td className="px-4 py-3 font-medium text-white">{entry.gpuModel}</td>
                      <td className="px-4 py-3 text-slate-400">
                        {entry.vramMb >= 1024
                          ? `${(entry.vramMb / 1024).toFixed(0)} GB`
                          : `${entry.vramMb} MB`}
                      </td>
                      <td className="px-4 py-3">
                        <span className="font-mono text-violet-300">{entry.modelId}</span>
                      </td>
                      <td className="px-4 py-3">
                        <span className="rounded bg-white/[0.06] px-2 py-0.5 text-xs font-mono text-slate-300 border border-white/[0.08]">
                          {entry.quantization}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-right font-semibold text-emerald-400">
                        {entry.tpsP50.toFixed(1)}
                      </td>
                      <td className="px-4 py-3 text-right text-slate-300">
                        {entry.firstTokenLatencyMs.toFixed(0)}ms
                      </td>
                      <td className="px-4 py-3 text-right">
                        <SuccessBadge rate={entry.successRate} />
                      </td>
                      <td className="px-4 py-3 text-right text-slate-500">
                        {entry.measurementCount.toLocaleString()}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Footer note */}
        {!loading && entries.length > 0 && (
          <p className="mt-4 text-xs text-slate-600 text-center">
            Performance data is aggregated and anonymised. Tokens/sec shown at p50 (median).
            Results vary by system load, context length, and driver version.
          </p>
        )}
      </div>
    </div>
  );
}
