"use client";

import { useState } from "react";

interface Plan {
  id: number;
  name: string;
  slug: string;
  description: string | null;
  price_monthly: number;
  price_yearly: number;
  credits_monthly: number;
  features: string[];
  stripe_monthly_price_id: string | null;
  stripe_yearly_price_id: string | null;
}

interface Props {
  plans: Plan[];
  currentPlanSlug: string | null;
  isLoggedIn: boolean;
}

const tierStyles: Record<string, { ring: string; badge: string; glow: string }> = {
  free: {
    ring: "border-surface-light",
    badge: "bg-surface-light text-text-muted",
    glow: "",
  },
  basic: {
    ring: "border-blue-500/40",
    badge: "bg-blue-500/20 text-blue-400",
    glow: "",
  },
  premium: {
    ring: "border-primary/60",
    badge: "bg-primary/20 text-primary",
    glow: "shadow-glow",
  },
  vip: {
    ring: "border-vip/60",
    badge: "bg-vip/20 text-vip",
    glow: "shadow-[0_0_30px_rgba(251,191,36,0.2)]",
  },
};

export default function PricingCards({ plans, currentPlanSlug, isLoggedIn }: Props) {
  const [billing, setBilling] = useState<"monthly" | "yearly">("monthly");
  const [loading, setLoading] = useState<string | null>(null);

  async function handleSubscribe(planSlug: string) {
    if (!isLoggedIn) {
      window.location.href = `/login?callbackUrl=/pricing`;
      return;
    }
    setLoading(planSlug);
    try {
      const res = await fetch("/api/subscriptions/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ plan_slug: planSlug, billing }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        alert(data.error || "Failed to create checkout session");
      }
    } catch {
      alert("An error occurred. Please try again.");
    } finally {
      setLoading(null);
    }
  }

  return (
    <>
      {/* Billing Toggle */}
      <div className="flex items-center justify-center gap-4 mb-10">
        <span
          className={`text-sm font-medium transition-colors ${
            billing === "monthly" ? "text-text" : "text-text-muted"
          }`}
        >
          Monthly
        </span>
        <button
          onClick={() => setBilling(billing === "monthly" ? "yearly" : "monthly")}
          className={`relative w-14 h-7 rounded-full transition-colors ${
            billing === "yearly" ? "bg-primary" : "bg-surface-light"
          }`}
        >
          <span
            className={`absolute top-0.5 left-0.5 w-6 h-6 bg-white rounded-full transition-transform ${
              billing === "yearly" ? "translate-x-7" : ""
            }`}
          />
        </button>
        <span
          className={`text-sm font-medium transition-colors ${
            billing === "yearly" ? "text-text" : "text-text-muted"
          }`}
        >
          Yearly{" "}
          <span className="text-green-400 text-xs font-semibold">Save 20%</span>
        </span>
      </div>

      {/* Plan Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {plans.map((plan) => {
          const style = tierStyles[plan.slug] || tierStyles.free;
          const isCurrent = currentPlanSlug === plan.slug;
          const price =
            billing === "monthly" ? plan.price_monthly : plan.price_yearly;
          const isFree = plan.slug === "free";
          const isPopular = plan.slug === "premium";

          return (
            <div
              key={plan.id}
              className={`relative bg-surface rounded-2xl border-2 ${style.ring} ${style.glow} p-6 flex flex-col transition-all hover:scale-[1.02]`}
            >
              {isPopular && (
                <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                  <span className="gradient-gold text-black text-xs font-bold px-4 py-1 rounded-full">
                    Most Popular
                  </span>
                </div>
              )}

              {isCurrent && (
                <div className="absolute -top-3 right-4">
                  <span className="bg-green-500 text-white text-xs font-bold px-3 py-1 rounded-full">
                    Current Plan
                  </span>
                </div>
              )}

              <div className="mb-4">
                <span className={`inline-block px-3 py-1 rounded-full text-xs font-semibold ${style.badge}`}>
                  {plan.name}
                </span>
              </div>

              <div className="mb-2">
                {isFree ? (
                  <div className="text-4xl font-bold text-text">Free</div>
                ) : (
                  <>
                    <div className="text-4xl font-bold text-text">
                      ${price.toFixed(2)}
                    </div>
                    <div className="text-text-muted text-sm">
                      /{billing === "monthly" ? "month" : "year"}
                    </div>
                  </>
                )}
              </div>

              {plan.credits_monthly > 0 && (
                <div className="text-primary text-sm font-medium mb-4">
                  +{plan.credits_monthly} credits/month
                </div>
              )}

              {plan.description && (
                <p className="text-text-muted text-sm mb-6">{plan.description}</p>
              )}

              <ul className="space-y-3 mb-8 flex-1">
                {plan.features.map((feature: string, i: number) => (
                  <li key={i} className="flex items-start gap-2 text-sm">
                    <svg
                      className="w-5 h-5 text-green-400 shrink-0 mt-0.5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M5 13l4 4L19 7"
                      />
                    </svg>
                    <span className="text-text-muted">{feature}</span>
                  </li>
                ))}
              </ul>

              {isFree ? (
                <div className="py-3 rounded-xl text-center text-text-muted border border-surface-light text-sm font-medium">
                  {isCurrent ? "Your Plan" : "Default Plan"}
                </div>
              ) : isCurrent ? (
                <div className="py-3 rounded-xl text-center text-green-400 bg-green-500/10 border border-green-500/30 text-sm font-medium">
                  Active Subscription
                </div>
              ) : (
                <button
                  onClick={() => handleSubscribe(plan.slug)}
                  disabled={loading !== null}
                  className={`w-full py-3 rounded-xl font-semibold transition-all disabled:opacity-50 ${
                    plan.slug === "vip"
                      ? "gradient-gold text-black hover:opacity-90"
                      : plan.slug === "premium"
                      ? "bg-primary hover:bg-primary-dark text-white"
                      : "bg-surface-light hover:bg-primary/20 text-text border border-surface-light hover:border-primary"
                  }`}
                >
                  {loading === plan.slug ? "Redirecting..." : "Subscribe"}
                </button>
              )}
            </div>
          );
        })}
      </div>
    </>
  );
}
