"use client";

import { useState } from "react";
import { motion, useReducedMotion } from "motion/react";
import { Gpu, TrendingDown, Zap } from "lucide-react";
import { cn } from "@/lib/utils";
import { GlassContainer } from "./GlassContainer";

interface GpuOption {
  name: string;
  vram: number;
  tokPerSec: number; // estimated tokens/sec for a 7B model
  costPerHour: number; // electricity cost estimate $/hr
}

const GPU_OPTIONS: GpuOption[] = [
  { name: "RTX 4060 (8 GB)", vram: 8, tokPerSec: 35, costPerHour: 0.03 },
  { name: "RTX 4060 Ti (16 GB)", vram: 16, tokPerSec: 45, costPerHour: 0.04 },
  { name: "RTX 4070 Ti (12 GB)", vram: 12, tokPerSec: 55, costPerHour: 0.05 },
  { name: "RTX 4080 (16 GB)", vram: 16, tokPerSec: 70, costPerHour: 0.06 },
  { name: "RTX 4090 (24 GB)", vram: 24, tokPerSec: 100, costPerHour: 0.08 },
  { name: "RTX 5090 (32 GB)", vram: 32, tokPerSec: 140, costPerHour: 0.10 },
  { name: "A100 (80 GB)", vram: 80, tokPerSec: 180, costPerHour: 0.25 },
  { name: "Mac Mini M4 Pro", vram: 24, tokPerSec: 50, costPerHour: 0.01 },
];

const USAGE_PRESETS = [
  { label: "Hobby", monthlyTokensM: 1, desc: "~1M tokens/mo" },
  { label: "Developer", monthlyTokensM: 10, desc: "~10M tokens/mo" },
  { label: "Team", monthlyTokensM: 50, desc: "~50M tokens/mo" },
  { label: "Production", monthlyTokensM: 200, desc: "~200M tokens/mo" },
];

// Cloud API pricing per 1M tokens (blended input/output average)
const CLOUD_COST_PER_M = 3.0; // ~$3/1M tokens average across GPT-4o-mini, Claude Haiku, etc.

function formatDollars(n: number): string {
  if (n < 1) return `$${n.toFixed(2)}`;
  if (n >= 1000) return `$${(n / 1000).toFixed(1)}K`;
  return `$${Math.round(n)}`;
}

export function SavingsCalculator() {
  const [gpuIdx, setGpuIdx] = useState(4); // RTX 4090 default
  const [usageIdx, setUsageIdx] = useState(1); // Developer default
  const reduced = useReducedMotion();

  const gpu = GPU_OPTIONS[gpuIdx];
  const usage = USAGE_PRESETS[usageIdx];

  // Calculate costs
  const cloudCost = usage.monthlyTokensM * CLOUD_COST_PER_M;
  // Local cost = electricity only (GPU running hours to process monthly tokens)
  // tokens/sec * 3600 = tokens/hr, monthly hours = monthlyTokens / tokens_per_hr
  const tokensPerHour = gpu.tokPerSec * 3600;
  const hoursNeeded = (usage.monthlyTokensM * 1_000_000) / tokensPerHour;
  const localCost = hoursNeeded * gpu.costPerHour;
  const savings = cloudCost - localCost;
  const savingsPercent = cloudCost > 0 ? Math.round((savings / cloudCost) * 100) : 0;

  return (
    <GlassContainer intensity="subtle" className="p-6 sm:p-8">
      <div className="grid gap-8 lg:grid-cols-2">
        {/* Left: Controls */}
        <div className="space-y-6">
          {/* GPU Selector */}
          <div>
            <label className="text-sm font-medium text-gray-300 mb-3 block">
              Your GPU
            </label>
            <div className="grid grid-cols-2 gap-2">
              {GPU_OPTIONS.map((g, i) => (
                <button
                  key={g.name}
                  onClick={() => setGpuIdx(i)}
                  className={cn(
                    "rounded-lg px-3 py-2 text-left text-xs transition-all border",
                    i === gpuIdx
                      ? "bg-violet-500/15 border-violet-500/40 text-violet-200"
                      : "bg-white/[0.03] border-white/[0.06] text-gray-400 hover:border-white/15 hover:text-gray-300"
                  )}
                >
                  <div className="font-medium">{g.name}</div>
                  <div className="text-[10px] opacity-60 mt-0.5">{g.vram}GB VRAM</div>
                </button>
              ))}
            </div>
          </div>

          {/* Usage Selector */}
          <div>
            <label className="text-sm font-medium text-gray-300 mb-3 block">
              Monthly Usage
            </label>
            <div className="flex gap-2">
              {USAGE_PRESETS.map((u, i) => (
                <button
                  key={u.label}
                  onClick={() => setUsageIdx(i)}
                  className={cn(
                    "flex-1 rounded-lg px-3 py-2.5 text-center text-xs transition-all border",
                    i === usageIdx
                      ? "bg-violet-500/15 border-violet-500/40 text-violet-200"
                      : "bg-white/[0.03] border-white/[0.06] text-gray-400 hover:border-white/15"
                  )}
                >
                  <div className="font-medium">{u.label}</div>
                  <div className="text-[10px] opacity-60 mt-0.5">{u.desc}</div>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Right: Results */}
        <div className="flex flex-col justify-center">
          <motion.div
            key={`${gpuIdx}-${usageIdx}`}
            initial={reduced ? {} : { opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3 }}
            className="space-y-4"
          >
            {/* Savings headline */}
            <div className="text-center lg:text-left">
              <div className="text-xs uppercase tracking-wider text-gray-500 mb-1">
                Monthly savings with LLMHosts
              </div>
              <div className="text-4xl sm:text-5xl font-bold text-white">
                {formatDollars(savings)}
                <span className="text-lg text-emerald-400 ml-2">
                  /{savingsPercent}% less
                </span>
              </div>
            </div>

            {/* Comparison bars */}
            <div className="space-y-3">
              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="text-gray-400">Cloud APIs</span>
                  <span className="text-gray-300">{formatDollars(cloudCost)}/mo</span>
                </div>
                <div className="h-3 rounded-full bg-white/[0.06] overflow-hidden">
                  <motion.div
                    className="h-full rounded-full bg-red-500/60"
                    initial={{ width: 0 }}
                    animate={{ width: "100%" }}
                    transition={{ duration: 0.6, ease: "easeOut" }}
                  />
                </div>
              </div>
              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="text-gray-400">LLMHosts (electricity only)</span>
                  <span className="text-emerald-400">{formatDollars(localCost)}/mo</span>
                </div>
                <div className="h-3 rounded-full bg-white/[0.06] overflow-hidden">
                  <motion.div
                    className="h-full rounded-full bg-emerald-500/60"
                    initial={{ width: 0 }}
                    animate={{
                      width: `${Math.max(1, (localCost / cloudCost) * 100)}%`,
                    }}
                    transition={{ duration: 0.6, delay: 0.1, ease: "easeOut" }}
                  />
                </div>
              </div>
            </div>

            {/* Quick stats */}
            <div className="grid grid-cols-3 gap-3 pt-2">
              {[
                {
                  icon: TrendingDown,
                  label: "Cost per 1M tokens",
                  value: formatDollars(localCost / Math.max(usage.monthlyTokensM, 0.1)),
                },
                {
                  icon: Zap,
                  label: "Throughput",
                  value: `${gpu.tokPerSec} tok/s`,
                },
                {
                  icon: Gpu,
                  label: "Annual savings",
                  value: formatDollars(savings * 12),
                },
              ].map((stat) => (
                <div
                  key={stat.label}
                  className="rounded-lg bg-white/[0.03] border border-white/[0.06] p-2.5 text-center"
                >
                  <stat.icon className="h-3.5 w-3.5 text-violet-400 mx-auto mb-1" />
                  <div className="text-xs font-semibold text-white">{stat.value}</div>
                  <div className="text-[9px] text-gray-500 mt-0.5">{stat.label}</div>
                </div>
              ))}
            </div>
          </motion.div>
        </div>
      </div>
    </GlassContainer>
  );
}
