"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Star, X, CreditCard, RefreshCw } from "lucide-react";

type Plan = {
  id: string;
  tier: string;
  name: string;
  price: number;
  interval: string;
  features: string;
  sortOrder: number;
};

const TIER_RANK: Record<string, number> = { free: 0, starter: 1, plus: 2, premium: 3 };

export default function ManageSubscriptionClient({ plans, currentTier }: { plans: Plan[]; currentTier: string }) {
  const router = useRouter();
  const [canceling, setCanceling] = useState(false);
  const [error, setError] = useState("");
  const [switchingTier, setSwitchingTier] = useState<string | null>(null);

  const current = plans.find((p) => p.tier === currentTier);
  const otherPlans = plans.filter((p) => p.tier !== currentTier && p.tier !== "free");
  const currentFeatures: string[] = current ? JSON.parse(current.features) : [];

  async function cancelMembership() {
    if (!confirm("Cancel your membership? You'll lose access to paid content at the end of your billing period.")) {
      return;
    }
    setCanceling(true);
    setError("");
    const res = await fetch("/api/subscription/cancel", { method: "POST" });
    const data = await res.json();
    setCanceling(false);
    if (!res.ok) {
      setError(data.error || "Something went wrong.");
      return;
    }
    router.refresh();
  }

  function switchPlan(plan: Plan) {
    setSwitchingTier(plan.tier);
    const params = new URLSearchParams({
      amount: String(plan.price),
      description: `${plan.name} Membership`,
      tier: plan.tier,
      interval: plan.interval || "month",
    });
    router.push(`/subscription/checkout?${params.toString()}`);
  }

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-2xl font-bold mb-1">Manage Membership</h1>
      <p className="text-neutral-400 text-sm mb-6">View your current membership and benefits.</p>

      {error && <p className="text-red-500 text-sm mb-4">{error}</p>}

      {currentTier === "free" ? (
        <div className="card p-6 mb-6 text-center">
          <p className="font-semibold mb-2">You're currently on the Free plan.</p>
          <p className="text-neutral-400 text-sm mb-4">Upgrade anytime to unlock more devotional content.</p>
          <Link href="/subscription/plans" className="btn-primary inline-block px-6 py-2.5">
            View Membership Plans
          </Link>
        </div>
      ) : (
        <>
          {/* Current plan card */}
          <div className="rounded-xl p-6 mb-6 bg-gradient-to-br from-red-700 to-red-900 relative overflow-hidden">
            <div className="flex items-start justify-between mb-2">
              <div className="flex items-center gap-2">
                <Star size={22} className="text-white" fill="currentColor" />
                <h2 className="text-xl font-bold">{current?.name || currentTier} Membership</h2>
              </div>
              <span className="bg-white/20 text-white text-xs font-semibold px-3 py-1 rounded-full">✓ Active</span>
            </div>
            <div className="flex items-center gap-2 mb-2">
              <span className="bg-black/30 text-xs px-2 py-1 rounded-full">Tier {TIER_RANK[currentTier]}</span>
              <span className="font-bold">${current?.price.toFixed(2)}/{current?.interval || "month"}</span>
            </div>
            <p className="text-sm text-white/80 mb-4">✓ Active subscription — renews automatically</p>
            <div className="flex gap-3">
              <button
                onClick={cancelMembership}
                disabled={canceling}
                className="flex items-center gap-2 bg-white/10 hover:bg-white/20 border border-white/30 rounded-lg px-4 py-2 text-sm font-semibold"
              >
                <X size={16} /> {canceling ? "Canceling..." : "Cancel Membership"}
              </button>
              <Link
                href="/payment-methods"
                className="flex items-center gap-2 bg-white hover:bg-neutral-100 rounded-lg px-4 py-2 text-sm font-semibold"
                style={{ color: "#1a1a1a" }}
              >
                <CreditCard size={16} /> Update Payment
              </Link>
            </div>
          </div>

          {/* Benefits */}
          <div className="card p-6 mb-6">
            <h3 className="font-bold mb-1">Your {current?.name} Benefits</h3>
            <p className="text-neutral-400 text-sm mb-4">Full access to your plan's content and features.</p>
            <div className="grid sm:grid-cols-2 gap-3">
              {currentFeatures.map((f, i) => (
                <div key={i} className="flex items-start gap-2 bg-neutral-900 rounded-lg p-3">
                  <span className="text-green-500 mt-0.5">✓</span>
                  <span className="text-sm">{f}</span>
                </div>
              ))}
            </div>
          </div>
        </>
      )}

      {/* Upgrade/switch plans */}
      {otherPlans.length > 0 && (
        <div className="card p-6">
          <div className="flex items-center gap-2 mb-1">
            <RefreshCw size={18} />
            <h3 className="font-bold">Upgrade or Change Plan</h3>
          </div>
          <p className="text-neutral-400 text-sm mb-4">Explore other plans available to you.</p>
          <div className="grid sm:grid-cols-2 gap-4">
            {otherPlans.map((p) => {
              const features: string[] = JSON.parse(p.features);
              return (
                <div key={p.id} className="border border-neutral-800 rounded-lg p-4">
                  <span className="text-xs bg-neutral-800 px-2 py-0.5 rounded-full">Tier {TIER_RANK[p.tier]}</span>
                  <h4 className="font-bold mt-2">{p.name}</h4>
                  <p className="text-xl font-bold mt-1">${p.price.toFixed(2)}<span className="text-xs text-neutral-500 font-normal">/{p.interval}</span></p>
                  <ul className="text-xs text-neutral-400 mt-2 space-y-1 mb-4">
                    {features.slice(0, 2).map((f, i) => <li key={i}>• {f}</li>)}
                  </ul>
                  <button
                    onClick={() => switchPlan(p)}
                    disabled={switchingTier !== null}
                    className="btn-primary w-full py-2 text-sm disabled:opacity-60"
                  >
                    {switchingTier === p.tier ? "Switching..." : "Switch to this plan"}
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
