"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Check, ShieldCheck, Lock } from "lucide-react";
import { PLANS, type PlanKey } from "@/lib/plans";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { GlowCard } from "@/components/ui/GlowCard";
import { AnimatedSection, AnimatedItem } from "@/components/ui/AnimatedSection";
import { PricingToggle } from "@/components/ui/PricingToggle";
import { FaqAccordion } from "@/components/ui/FaqAccordion";
import { CostCalculator } from "@/components/ui/CostCalculator";

const PLAN_ORDER: PlanKey[] = ["free", "pro", "team", "enterprise"];

import { FAQ_ITEMS } from "./faq-data";

export default function PricingPageClient() {
  const router = useRouter();
  const [loading, setLoading] = useState<string | null>(null);
  const [billing, setBilling] = useState<"monthly" | "annual">("monthly");

  async function handleSubscribe(planKey: PlanKey) {
    if (planKey === "free") {
      window.open("https://pypi.org/project/llmhosts/", "_blank");
      return;
    }

    if (planKey === "enterprise") {
      router.push("/contact?subject=Enterprise+inquiry");
      return;
    }

    setLoading(planKey);

    try {
      const response = await fetch("/api/stripe/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan: planKey }),
      });

      const data = (await response.json()) as { url?: string; error?: string };

      if (!response.ok) {
        if (response.status === 401) {
          router.push("/auth/login?callbackUrl=/pricing");
          return;
        }
        throw new Error(data.error ?? "Failed to create checkout session");
      }

      if (data.url) window.location.href = data.url;
    } catch (error) {
      console.error("Checkout error:", error);
      alert("Something went wrong. Please try again.");
    } finally {
      setLoading(null);
    }
  }

  return (
    <div className="min-h-screen" style={{ background: "#080809" }}>
      {/* Header */}
      <div className="mx-auto max-w-7xl px-4 pt-20 pb-12 text-center sm:px-6 lg:px-8">
        <AnimatedSection>
          <AnimatedItem>
            <h1
              className="text-4xl font-bold text-white sm:text-5xl"
              style={{ letterSpacing: "-0.03em" }}
            >
              Simple, transparent pricing
            </h1>
            <p className="mx-auto mt-4 max-w-2xl text-lg text-gray-400">
              Local inference free forever. Pay only for cloud intelligence and coordination.
            </p>
          </AnimatedItem>
          <AnimatedItem>
            <div className="mt-8 flex justify-center">
              <PricingToggle value={billing} onChange={setBilling} />
            </div>
          </AnimatedItem>
        </AnimatedSection>
      </div>

      {/* Pricing Grid */}
      <div className="mx-auto max-w-7xl px-4 pb-16 sm:px-6 lg:px-8">
        <AnimatedSection
          className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4"
          stagger={0.08}
        >
          {PLAN_ORDER.map((planKey) => {
            const plan = PLANS[planKey];
            const isPopular = planKey === "pro";
            const isEnterprise = planKey === "enterprise";
            const isFree = planKey === "free";
            const annualPrice = plan.price > 0 ? Math.round(plan.price * 0.8) : 0;
            const displayPrice =
              billing === "annual" && plan.price > 0 ? annualPrice : plan.price;

            return (
              <AnimatedItem key={planKey}>
                <GlowCard
                  className={cn(
                    "flex h-full flex-col p-6",
                    isPopular && "ring-2 ring-violet-500/50 shadow-xl shadow-violet-500/10",
                  )}
                >
                  {isPopular && (
                    <div className="mb-4">
                      <span className="inline-flex items-center rounded-full bg-violet-600 px-3 py-0.5 text-xs font-semibold text-white">
                        Most Popular
                      </span>
                    </div>
                  )}

                  <div className="mb-4">
                    <h3 className="text-base font-semibold text-white">{plan.name}</h3>
                    <p className="mt-1 text-sm text-gray-400">{plan.description}</p>
                  </div>

                  <div className="mb-6">
                    {isEnterprise ? (
                      <div className="text-3xl font-bold text-white">Custom</div>
                    ) : (
                      <div className="flex items-baseline gap-1">
                        <span className="text-3xl font-bold text-white">${displayPrice}</span>
                        {displayPrice > 0 && (
                          <span className="text-sm text-gray-400">
                            /{planKey === "team" ? "seat/" : ""}mo
                          </span>
                        )}
                        {isFree && (
                          <span className="ml-1 text-sm text-gray-400">forever</span>
                        )}
                      </div>
                    )}
                    {billing === "annual" && plan.price > 0 && !isEnterprise && (
                      <p className="mt-1 text-xs text-emerald-400">Billed annually · Save 20%</p>
                    )}
                  </div>

                  <div className="mb-6 border-t border-white/[0.06]" />

                  <ul className="mb-8 flex-1 space-y-3">
                    {plan.features.map((feature) => (
                      <li key={feature} className="flex items-start gap-3">
                        <Check className="mt-0.5 h-4 w-4 shrink-0 text-violet-400" />
                        <span className="text-sm text-gray-300">{feature}</span>
                      </li>
                    ))}
                  </ul>

                  <Button
                    variant={isFree ? "ghost" : isEnterprise ? "secondary" : "primary"}
                    size="lg"
                    className={cn(
                      "w-full",
                      isPopular &&
                        "bg-violet-600 shadow-lg shadow-violet-500/25 hover:bg-violet-500",
                      (isFree || isEnterprise) && "border-white/10 hover:bg-white/5",
                    )}
                    onClick={() => handleSubscribe(planKey)}
                    disabled={loading === planKey}
                  >
                    {loading === planKey ? "Processing..." : plan.cta}
                  </Button>
                </GlowCard>
              </AnimatedItem>
            );
          })}
        </AnimatedSection>

        {/* Trust signals */}
        <div className="mt-8 flex flex-wrap items-center justify-center gap-6 text-sm text-gray-400">
          <span className="flex items-center gap-1.5">
            <Lock className="h-4 w-4 text-emerald-400" />
            256-bit SSL encrypted
          </span>
          <span className="flex items-center gap-1.5">
            <ShieldCheck className="h-4 w-4 text-violet-400" />
            Powered by Stripe
          </span>
          <span className="flex items-center gap-1.5">
            <Check className="h-4 w-4 text-blue-400" />
            Cancel anytime
          </span>
        </div>

        <div className="mt-4 text-center text-sm text-gray-400">
          No credit card required for free tier · 30-day satisfaction guarantee
        </div>
      </div>

      {/* Cost Calculator */}
      <div className="mx-auto max-w-7xl px-4 pb-16 sm:px-6 lg:px-8">
        <AnimatedSection>
          <AnimatedItem>
            <CostCalculator />
          </AnimatedItem>
        </AnimatedSection>
      </div>

      {/* FAQ */}
      <div className="mx-auto max-w-2xl px-4 pb-24 sm:px-6 lg:px-8">
        <AnimatedSection>
          <AnimatedItem>
            <h2 className="mb-8 text-center text-xl font-semibold text-white">
              Frequently asked questions
            </h2>
          </AnimatedItem>
          <AnimatedItem>
            <div className="glass rounded-xl p-6">
              <FaqAccordion items={FAQ_ITEMS} />
            </div>
          </AnimatedItem>
        </AnimatedSection>

        <div className="mt-8 text-center">
          <p className="text-sm text-gray-400">
            More questions?{" "}
            <a
              href="/contact"
              className="text-violet-400 underline hover:text-violet-300 transition-colors"
            >
              Get in touch
            </a>
          </p>
        </div>
      </div>
    </div>
  );
}
