"use client";

import { useState } from "react";
import { Check, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { motion, AnimatePresence } from "motion/react";
import Link from "next/link";

type Cycle = "monthly" | "quarterly" | "yearly";

const cycles: { key: Cycle; label: string; badge?: string }[] = [
  { key: "monthly",   label: "Monthly" },
  { key: "quarterly", label: "Quarterly", badge: "Save 10%" },
  { key: "yearly",    label: "Yearly",    badge: "Save 20%" },
];

const pricingPlans = [
  {
    name: "CORE",
    tagline: "Stable & Economical",
    prices: { monthly: "Rp 15.000", quarterly: "Rp 13.500", yearly: "Rp 12.000" },
    description: "Ideal for websites, Discord bots, and lightweight databases.",
    features: [
      "From 1 vCPU Core",
      "From 1 GB RAM",
      "From 5 GB NVMe SSD",
      "1 Gbps Network Port",
      "Standard DDoS Protection",
      "24/7 Technical Support",
    ],
    highlight: false,
    linkId: "core",
    accentColor: "text-emerald-400",
    checkBg: "bg-emerald-500/10",
    checkColor: "text-emerald-400",
  },
  {
    name: "FLUX",
    tagline: "High Performance Gaming",
    prices: { monthly: "Rp 20.000", quarterly: "Rp 18.000", yearly: "Rp 16.000" },
    description: "High performance with fast clock speeds tailored for game servers.",
    features: [
      "From 2 vCPU High-Freq",
      "From 2 GB DDR4 RAM",
      "From 512 GB NVMe Gen 4",
      "10 Gbps Network Port",
      "Advanced Game DDoS",
      "Priority Support Routing",
    ],
    highlight: true,
    linkId: "flux",
    accentColor: "text-accent-text",
    checkBg: "bg-accent-hover/15",
    checkColor: "text-accent-text/80",
  },
  {
    name: "ATLAS",
    tagline: "Extreme Compute",
    prices: { monthly: "Rp 30.000", quarterly: "Rp 27.000", yearly: "Rp 24.000" },
    description: "Full power for enterprise, Mega SMPs, and heavy workloads.",
    features: [
      "From 2 CPU Dedicated",
      "Up to 32 GB DDR5 RAM",
      "Up to 2 TB Enterprise NVMe",
      "L7 Custom Mitigation",
      "Dedicated Account Manager",
    ],
    highlight: false,
    linkId: "atlas",
    accentColor: "text-indigo-400",
    checkBg: "bg-indigo-500/10",
    checkColor: "text-indigo-400",
  },
];

const cycleSuffix: Record<Cycle, string> = {
  monthly:   "/mo",
  quarterly: "/mo · billed quarterly",
  yearly:    "/mo · billed yearly",
};

const PricingCard = ({
  plan,
  index,
  cycle,
}: {
  plan: typeof pricingPlans[0];
  index: number;
  cycle: Cycle;
}) => (
  <motion.div
    initial={{ opacity: 0, y: 28 }}
    whileInView={{ opacity: 1, y: 0 }}
    viewport={{ once: true }}
    transition={{ duration: 0.5, delay: index * 0.1, ease: "easeOut" }}
    className={cn(
      "relative flex flex-col rounded-2xl border p-8 h-full",
      plan.highlight
        ? "border-accent-hover/40 bg-accent/4"
        : "border-white/6 bg-surface hover:border-white/10 hover:bg-elevated transition-colors duration-300"
    )}
  >
    {plan.highlight && (
      <div className="absolute -top-3.5 left-1/2 -translate-x-1/2 z-10">
        <span className="inline-flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full border border-accent-hover/30 bg-zinc-950 text-accent-text whitespace-nowrap">
          Most Popular
        </span>
      </div>
    )}

    <p className="text-[10px] font-bold uppercase tracking-widest text-content-subtle mb-3">{plan.name}</p>

    <div className="mb-1">
      <AnimatePresence mode="wait">
        <motion.span
          key={cycle}
          initial={{ opacity: 0, y: -6 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 6 }}
          transition={{ duration: 0.18 }}
          className="text-4xl sm:text-5xl font-bold tracking-tighter text-white block"
        >
          {plan.prices[cycle]}
        </motion.span>
      </AnimatePresence>
      <span className="text-content-muted text-xs">{cycleSuffix[cycle]}</span>
    </div>

    <p className={cn("text-[10px] font-bold uppercase tracking-widest mb-6 mt-3", plan.accentColor)}>{plan.tagline}</p>

    <p className="text-sm text-content-dim leading-relaxed mb-6">{plan.description}</p>

    <div className="h-px bg-white/5 mb-6" />

    <ul className="space-y-3 flex-1 mb-8">
      {plan.features.map((feature, idx) => (
        <li key={idx} className="flex items-start gap-2.5 text-sm">
          <div className={cn("mt-0.5 p-0.5 rounded-full shrink-0", plan.checkBg)}>
            <Check className={cn("w-3 h-3", plan.checkColor)} />
          </div>
          <span className="text-content-dim">{feature}</span>
        </li>
      ))}
    </ul>

    <Link href={`/game-host?plan=${plan.linkId}`} className="block mt-auto">
      <button
        className={cn(
          "w-full flex items-center justify-center gap-2 py-3 rounded-xl font-semibold text-sm transition-all duration-150 group/btn",
          plan.highlight
            ? "bg-accent hover:bg-accent-hover text-white shadow-[0_4px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:shadow-[0_6px_0_rgba(0,0,0,0.35),inset_0_1px_0_rgba(255,255,255,0.12)] hover:-translate-y-0.5 active:translate-y-1 active:shadow-none"
            : "bg-zinc-900 border border-border/80 text-zinc-300 hover:bg-zinc-800 hover:text-white hover:border-border-hover shadow-[0_3px_0_rgba(0,0,0,0.5)] hover:shadow-[0_4px_0_rgba(0,0,0,0.5)] hover:-translate-y-0.5 active:translate-y-1 active:shadow-none"
        )}
      >
        Get Started
        <ArrowRight className="w-3.5 h-3.5 opacity-60 group-hover/btn:translate-x-0.5 group-hover/btn:opacity-100 transition-all duration-200" />
      </button>
    </Link>
  </motion.div>
);

export default function PricingSection() {
  const [cycle, setCycle] = useState<Cycle>("monthly");

  return (
    <section
      id="pricing"
      className="relative w-full py-24 md:py-36 px-6 lg:px-12 overflow-hidden font-sans border-t border-border/80"
    >
      <div
        className="absolute inset-0 opacity-[0.025] pointer-events-none z-0"
        style={{
          backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
          backgroundSize: "128px 128px",
        }}
      />

      <div className="max-w-7xl mx-auto relative z-10">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.6, ease: "easeOut" }}
          className="mb-10 md:mb-12"
        >
          <div className="flex items-center gap-3 mb-6">
            <span className="block h-0.5 w-6 bg-accent-hover rounded-full" />
            <p className="text-xs font-bold text-accent-text uppercase tracking-widest">Transparent Pricing</p>
          </div>
          <h2 className="text-4xl md:text-5xl lg:text-6xl font-semibold tracking-tight text-white leading-[1.1] mb-4">
            Choose your <br />
            <span className="text-accent-text">power level.</span>
          </h2>
          <p className="text-content-dim max-w-lg text-[1rem] md:text-lg leading-relaxed">
            Flexible infrastructure for every need. Scale from a simple bot host to a massive gaming cluster.
          </p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 10 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.4, delay: 0.15 }}
          className="flex items-center gap-1 p-1 rounded-xl border border-border/80 bg-surface w-fit mb-12"
        >
          {cycles.map((c) => (
            <button
              key={c.key}
              onClick={() => setCycle(c.key)}
              className={cn(
                "relative flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition-all duration-200",
                cycle === c.key
                  ? "bg-accent text-white"
                  : "text-content-dim hover:text-white"
              )}
            >
              {c.label}
              {c.badge && (
                <span className={cn(
                  "text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded",
                  cycle === c.key
                    ? "bg-white/20 text-white"
                    : "bg-emerald-500/15 text-emerald-400"
                )}>
                  {c.badge}
                </span>
              )}
            </button>
          ))}
        </motion.div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 lg:gap-8 items-stretch">
          {pricingPlans.map((plan, index) => (
            <PricingCard key={plan.name} plan={plan} index={index} cycle={cycle} />
          ))}
        </div>

        <motion.p
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          viewport={{ once: true }}
          transition={{ duration: 0.5, delay: 0.4 }}
          className="text-center text-content-faint text-xs mt-12 tracking-wide"
        >
          All plans include instant deployment · No setup fees · Cancel anytime
        </motion.p>
      </div>
    </section>
  );
}
