"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import {
  Trophy,
  DollarSign,
  Flame,
  Zap,
  Route,
} from "lucide-react";
import { AchievementCard } from "@/components/achievement-card";
import {
  getAllAchievementsWithProgress,
  groupAchievementsByCategory,
  type UserProgress,
} from "@/lib/achievements";

const CATEGORY_HEADERS: Record<string, { label: string; icon: typeof Trophy }> = {
  savings: { label: "Savings milestones", icon: DollarSign },
  streak: { label: "Usage streaks", icon: Flame },
  cache: { label: "Cache efficiency", icon: Zap },
  routing: { label: "Routing badges", icon: Route },
};

const SAVINGS_PERCENT = 35;

function useAchievementProgress(): { progress: UserProgress; loading: boolean } {
  const [totalSpend, setTotalSpend] = useState(0);
  const [metricsData, setMetricsData] = useState({
    cacheHitRate: 0,
    localRequests: 0,
    totalRequests: 0,
  });
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      // Fetch cost data for savings calculation
      const costsRes = await fetch("/api/costs");
      if (costsRes.ok) {
        const costsData = await costsRes.json();
        setTotalSpend(costsData.totals?.total ?? 0);
      }

      // Fetch real-time proxy metrics
      const metricsRes = await fetch("/api/metrics");
      if (metricsRes.ok) {
        const metrics = await metricsRes.json();

        // Calculate local requests (ollama, vllm) vs remote (openai, anthropic, etc.)
        const localBackends = ["ollama", "vllm"];
        const localCount = Object.entries(metrics.by_backend || {})
          .filter(([backend]) => localBackends.includes(backend.toLowerCase()))
          .reduce((sum, [, count]) => sum + (count as number), 0);

        setMetricsData({
          cacheHitRate: metrics.cache_hit_rate ?? 0,
          localRequests: localCount,
          totalRequests: metrics.requests_total ?? 0,
        });
      }
    } catch {
      // empty state
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const progress = useMemo<UserProgress>(
    () => ({
      savingsTotal: totalSpend * (SAVINGS_PERCENT / 100),
      currentStreak: 0,  // TODO: Implement streak tracking
      longestStreak: 0,   // TODO: Implement streak tracking
      cacheHitRate: metricsData.cacheHitRate,
      localRequests: metricsData.localRequests,
      totalRequests: metricsData.totalRequests,
    }),
    [totalSpend, metricsData],
  );

  return { progress, loading };
}

export default function AchievementsPage() {
  const { progress, loading } = useAchievementProgress();
  const achievements = useMemo(
    () => getAllAchievementsWithProgress(progress),
    [progress],
  );
  const grouped = useMemo(
    () => groupAchievementsByCategory(achievements),
    [achievements],
  );

  const earnedCount = achievements.filter((a) => a.earned).length;
  const totalCount = achievements.length;

  if (loading) {
    return (
      <div className="space-y-8">
        <div>
          <h1 className="text-2xl font-bold text-white">Achievements</h1>
          <p className="mt-1 text-gray-400">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold text-white">Achievements</h1>
        <p className="mt-1 text-gray-400">
          Track your progress and unlock badges as you use LLMHosts.
        </p>
      </div>

      <div className="flex items-center gap-4 rounded-xl border border-gray-800 bg-gray-900 p-4">
        <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-indigo-500/20">
          <Trophy className="h-6 w-6 text-indigo-400" />
        </div>
        <div>
          <p className="text-sm font-medium text-gray-400">Overall progress</p>
          <p className="text-xl font-bold text-white">
            {earnedCount} / {totalCount} earned
          </p>
        </div>
      </div>

      <div className="space-y-10">
        {(["savings", "streak", "cache", "routing"] as const).map((cat) => {
          const items = grouped[cat];
          if (!items.length) return null;
          const meta = CATEGORY_HEADERS[cat];
          const Icon = meta.icon;
          return (
            <section key={cat}>
              <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-white">
                <Icon className="h-5 w-5 text-indigo-400" />
                {meta.label}
              </h2>
              <div className="grid gap-4 sm:grid-cols-2">
                {items.map((achievement) => (
                  <AchievementCard
                    key={achievement.id}
                    achievement={achievement}
                    compact={false}
                  />
                ))}
              </div>
            </section>
          );
        })}
      </div>
    </div>
  );
}
