"use client";
import { useState } from "react";

const PLANS = [
  { tier: "free", name: "Free", price: "$0", features: ["1 board", "50 feedback/mo", "\"Powered by\" badge"], cta: "Current" },
  { tier: "pro", name: "Pro", price: "$9/mo", features: ["5 boards", "Unlimited", "AI clustering", "Brand removal", "Webhooks"], cta: "Upgrade to Pro" },
  { tier: "team", name: "Team", price: "$19/mo", features: ["Everything in Pro", "20 boards", "SSO", "Analytics", "Founder support"], cta: "Upgrade to Team" },
] as const;

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

  async function checkout(target: "pro" | "team") {
    setLoading(target);
    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 {
      alert("Checkout failed. Polar may not be configured yet.");
    }
    setLoading(null);
  }

  async function cancel() {
    if (!confirm("Cancel subscription?")) return;
    setLoading("cancel");
    const res = await fetch("/api/proxy/billing/cancel", { method: "POST" });
    if (res.ok) setTier("free");
    setLoading(null);
  }

  return (
    <div className="space-y-6">
      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5 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">
            Cancel subscription
          </button>
        )}
      </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-brand-500/50 bg-brand-500/5" : "border-white/10 bg-ink-800/40"}`}>
              {isCurrent && <div className="text-xs font-mono text-brand-400 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-brand-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" | "team")} disabled={loading !== null}
                  className="w-full bg-brand-500 hover:bg-brand-400 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>
    </div>
  );
}
