"use client";

import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { TrendingDown, DollarSign, Zap, Activity } from "lucide-react";

interface ModelSaving {
  model: string;
  calls: number;
  cloudCostUsd: number;
  localCostUsd: number;
  savingsUsd: number;
}

interface DailySaving {
  date: string;
  savingsUsd: number;
}

interface SavingsData {
  totalSavingsUsd: number;
  totalCalls: number;
  avgSavingsPct: number;
  models: ModelSaving[];
  dailySavings: DailySaving[];
}

function formatCurrency(value: number): string {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value);
}

function formatDate(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

export default function SavingsPage() {
  const [data, setData] = useState<SavingsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/savings")
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json() as Promise<SavingsData>;
      })
      .then((d) => {
        setData(d);
        setLoading(false);
      })
      .catch((err: unknown) => {
        setError(err instanceof Error ? err.message : "Failed to load savings data");
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="flex items-center gap-3 text-gray-400">
          <Activity className="h-5 w-5 animate-pulse" />
          <span>Loading savings data…</span>
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-red-400">{error ?? "No savings data available."}</p>
      </div>
    );
  }

  const chartData = data.dailySavings.map((d) => ({
    ...d,
    label: formatDate(d.date),
  }));

  return (
    <div className="space-y-8">
      {/* Page header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-100">Savings Center</h1>
        <p className="mt-1 text-sm text-gray-400">
          Real-time comparison of local inference costs vs. cloud API pricing
        </p>
      </div>

      {/* Hero stats */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
        {/* Total saved */}
        <Card className="bg-gradient-to-br from-emerald-900/40 to-emerald-800/20 border-emerald-700/40 p-6">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-sm font-medium text-emerald-300">Total Saved</p>
              <p className="mt-2 text-4xl font-bold text-emerald-100">
                {formatCurrency(data.totalSavingsUsd)}
              </p>
              <p className="mt-1 text-xs text-emerald-400">vs. cloud API pricing</p>
            </div>
            <div className="rounded-full bg-emerald-500/20 p-3">
              <DollarSign className="h-6 w-6 text-emerald-400" />
            </div>
          </div>
        </Card>

        {/* Total calls */}
        <Card className="bg-gray-800/50 border-gray-700/50 p-6">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-sm font-medium text-gray-400">Total Inferences</p>
              <p className="mt-2 text-4xl font-bold text-gray-100">
                {data.totalCalls.toLocaleString()}
              </p>
              <p className="mt-1 text-xs text-gray-500">requests routed locally</p>
            </div>
            <div className="rounded-full bg-indigo-500/20 p-3">
              <Zap className="h-6 w-6 text-indigo-400" />
            </div>
          </div>
        </Card>

        {/* Avg savings % */}
        <Card className="bg-gray-800/50 border-gray-700/50 p-6">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-sm font-medium text-gray-400">Avg. Savings</p>
              <p className="mt-2 text-4xl font-bold text-gray-100">
                {data.avgSavingsPct.toFixed(1)}%
              </p>
              <p className="mt-1 text-xs text-gray-500">per inference call</p>
            </div>
            <div className="rounded-full bg-violet-500/20 p-3">
              <TrendingDown className="h-6 w-6 text-violet-400" />
            </div>
          </div>
        </Card>
      </div>

      {/* Daily savings chart */}
      <Card className="bg-gray-800/50 border-gray-700/50 p-6">
        <h2 className="mb-4 text-base font-semibold text-gray-200">Daily Savings (USD)</h2>
        <ResponsiveContainer width="100%" height={220}>
          <LineChart data={chartData} margin={{ top: 4, right: 16, left: 0, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
            <XAxis
              dataKey="label"
              tick={{ fill: "#9CA3AF", fontSize: 12 }}
              axisLine={false}
              tickLine={false}
            />
            <YAxis
              tick={{ fill: "#9CA3AF", fontSize: 12 }}
              axisLine={false}
              tickLine={false}
              tickFormatter={(v: number) => `$${v.toFixed(2)}`}
            />
            <Tooltip
              contentStyle={{
                backgroundColor: "#1F2937",
                border: "1px solid #374151",
                borderRadius: "8px",
              }}
              labelStyle={{ color: "#D1D5DB" }}
              formatter={(value: number | undefined) => [`$${(value ?? 0).toFixed(2)}`, "Saved"]}
            />
            <Line
              type="monotone"
              dataKey="savingsUsd"
              stroke="#34D399"
              strokeWidth={2}
              dot={{ fill: "#34D399", r: 4 }}
              activeDot={{ r: 6 }}
            />
          </LineChart>
        </ResponsiveContainer>
      </Card>

      {/* Per-model breakdown */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Bar chart */}
        <Card className="bg-gray-800/50 border-gray-700/50 p-6">
          <h2 className="mb-4 text-base font-semibold text-gray-200">Savings by Model</h2>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart
              data={data.models}
              margin={{ top: 4, right: 16, left: 0, bottom: 0 }}
              layout="vertical"
            >
              <CartesianGrid strokeDasharray="3 3" stroke="#374151" horizontal={false} />
              <XAxis
                type="number"
                tick={{ fill: "#9CA3AF", fontSize: 11 }}
                axisLine={false}
                tickLine={false}
                tickFormatter={(v: number) => `$${v.toFixed(2)}`}
              />
              <YAxis
                type="category"
                dataKey="model"
                tick={{ fill: "#9CA3AF", fontSize: 11 }}
                axisLine={false}
                tickLine={false}
                width={96}
              />
              <Tooltip
                contentStyle={{
                  backgroundColor: "#1F2937",
                  border: "1px solid #374151",
                  borderRadius: "8px",
                }}
                labelStyle={{ color: "#D1D5DB" }}
                formatter={(value: number | undefined) => [`$${(value ?? 0).toFixed(4)}`, ""]}
              />
              <Bar dataKey="cloudCostUsd" name="Cloud cost" fill="#6366F1" radius={[0, 4, 4, 0]} />
              <Bar dataKey="localCostUsd" name="Local cost" fill="#34D399" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Card>

        {/* Table breakdown */}
        <Card className="bg-gray-800/50 border-gray-700/50 p-6">
          <h2 className="mb-4 text-base font-semibold text-gray-200">Model Breakdown</h2>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-700">
                  <th className="pb-2 text-left font-medium text-gray-400">Model</th>
                  <th className="pb-2 text-right font-medium text-gray-400">Calls</th>
                  <th className="pb-2 text-right font-medium text-gray-400">Cloud</th>
                  <th className="pb-2 text-right font-medium text-gray-400">Local</th>
                  <th className="pb-2 text-right font-medium text-gray-400">Saved</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-700/50">
                {data.models.map((m) => {
                  const savingsPct =
                    m.cloudCostUsd > 0
                      ? ((m.savingsUsd / m.cloudCostUsd) * 100).toFixed(0)
                      : "0";
                  return (
                    <tr key={m.model} className="hover:bg-gray-700/20 transition-colors">
                      <td className="py-2 pr-3 font-mono text-xs text-gray-200">{m.model}</td>
                      <td className="py-2 text-right text-gray-300">{m.calls}</td>
                      <td className="py-2 text-right text-gray-300">
                        {formatCurrency(m.cloudCostUsd)}
                      </td>
                      <td className="py-2 text-right text-gray-300">
                        {formatCurrency(m.localCostUsd)}
                      </td>
                      <td className="py-2 text-right">
                        <span className="inline-flex items-center gap-1 text-emerald-400 font-medium">
                          {formatCurrency(m.savingsUsd)}
                          <span className="text-xs text-emerald-500">({savingsPct}%)</span>
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr className="border-t border-gray-700">
                  <td className="pt-3 font-semibold text-gray-200">Total</td>
                  <td className="pt-3 text-right font-semibold text-gray-200">
                    {data.totalCalls}
                  </td>
                  <td className="pt-3 text-right font-semibold text-gray-200">
                    {formatCurrency(
                      data.models.reduce((s, m) => s + m.cloudCostUsd, 0)
                    )}
                  </td>
                  <td className="pt-3 text-right font-semibold text-gray-200">
                    {formatCurrency(
                      data.models.reduce((s, m) => s + m.localCostUsd, 0)
                    )}
                  </td>
                  <td className="pt-3 text-right font-semibold text-emerald-400">
                    {formatCurrency(data.totalSavingsUsd)}
                  </td>
                </tr>
              </tfoot>
            </table>
          </div>
        </Card>
      </div>

      {/* Methodology note */}
      <Card className="bg-gray-800/30 border-gray-700/30 p-4">
        <p className="text-xs text-gray-500">
          <span className="font-medium text-gray-400">Methodology: </span>
          Cloud costs use Feb 2026 public pricing (GPT-4o, Claude 3.5 Sonnet, Gemini 1.5, Groq).
          Local costs reflect electricity consumption only, estimated at $0.12/kWh with per-model
          watt-hour profiles (7B: 0.3Wh/1k tokens → 70B: 3Wh/1k tokens). Actual savings may vary
          based on your electricity rate and hardware efficiency.
        </p>
      </Card>
    </div>
  );
}
