"use client";

import { useState } from "react";

const PLANS: Array<{
  tier: "free" | "pro" | "plus";
  name: string;
  price: string;
  features: string[];
  cta: string;
}> = [
  {
    tier: "free",
    name: "Free",
    price: "$0",
    features: ["1 alert type", "6h delay", "1 slot"],
    cta: "Current",
  },
  {
    tier: "pro",
    name: "Pro",
    price: "$9.99/mo",
    features: ["All alert types", "Real-time", "10 slots", "Multi-chain"],
    cta: "Upgrade to Pro",
  },
  {
    tier: "plus",
    name: "Plus",
    price: "$19.99/mo",
    features: ["Everything in Pro", "50 slots", "Webhook", "Discord", "API access"],
    cta: "Upgrade to Plus",
  },
];

export function BillingPanel({
  initial,
}: {
  initial: { tier: string; polarSubscriptionId: string | null; canceledAt: string | null };
}) {
  const [tier, setTier] = useState(initial.tier);
  const [loading, setLoading] = useState<string | null>(null);

  async function checkout(target: "pro" | "plus") {
    setLoading(target);
    try {
      const res = await fetch("/api/proxy/billing/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ tier: target }),
      });
      if (res.ok) {
        const { url } = await res.json();
        if (url) window.location.href = url;
      } else {
        const err = await res.json().catch(() => ({}));
        alert(`Checkout failed: ${err.message || err.error || "unknown"}`);
      }
    } finally {
      setLoading(null);
    }
  }

  async function cancel() {
    if (!confirm("Cancel your subscription? You'll drop to free at next renewal.")) return;
    setLoading("cancel");
    const res = await fetch("/api/proxy/billing/cancel", { method: "POST" });
    if (res.ok) {
      setTier("free");
    } else {
      alert("Cancel failed.");
    }
    setLoading(null);
  }

  return (
    <div className="space-y-6">
      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <div className="flex items-center justify-between">
          <div>
            <div className="text-xs uppercase text-white/40 font-mono mb-1">Current plan</div>
            <div className="text-2xl font-bold">{tier.toUpperCase()}</div>
          </div>
          {tier !== "free" && (
            <button
              onClick={cancel}
              disabled={loading !== null}
              className="text-sm text-red-400 hover:text-red-300 underline disabled:opacity-50"
            >
              Cancel subscription
            </button>
          )}
        </div>
      </div>

      <div className="grid md:grid-cols-3 gap-4">
        {PLANS.map((p) => {
          const isCurrent = p.tier === tier;
          const isUpgrade = p.tier !== "free" && p.tier !== tier;
          return (
            <div
              key={p.tier}
              className={`rounded-xl p-6 border ${
                isCurrent
                  ? "border-accent-500/50 bg-accent-500/5"
                  : "border-white/10 bg-ink-800/40"
              }`}
            >
              {isCurrent && (
                <div className="text-xs font-mono text-accent-glow uppercase mb-2">Current</div>
              )}
              <h3 className="font-bold text-xl mb-1">{p.name}</h3>
              <div className="text-2xl font-extrabold mb-4">{p.price}</div>
              <ul className="space-y-1.5 mb-6">
                {p.features.map((f) => (
                  <li key={f} className="text-sm text-white/70 flex gap-2">
                    <span className="text-accent-500">✓</span>
                    {f}
                  </li>
                ))}
              </ul>
              {isCurrent ? (
                <div className="bg-ink-700 text-white/40 text-center py-2 rounded-lg text-sm font-semibold">
                  {p.cta}
                </div>
              ) : isUpgrade ? (
                <button
                  onClick={() => checkout(p.tier as "pro" | "plus")}
                  disabled={loading !== null}
                  className="w-full bg-accent-500 hover:bg-accent-400 disabled:opacity-50 text-ink-950 font-bold py-2 rounded-lg text-sm"
                >
                  {loading === p.tier ? "Redirecting…" : p.cta}
                </button>
              ) : (
                <div className="text-center py-2 text-xs text-white/30">
                  Cancel current to downgrade
                </div>
              )}
            </div>
          );
        })}
      </div>

      <p className="text-xs text-white/40 text-center">
        Payments via Polar.sh · USDC or card · No long-term commitment
      </p>
    </div>
  );
}
