"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";

/**
 * Cancel a PayPal subscription. Stripe-managed subscriptions use the
 * "Manage subscription" Customer Portal button instead — this one only
 * appears when the user's Subscription row has `paypalSubscriptionId` set.
 */
export function CancelPaypalSubscriptionButton() {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  async function cancel() {
    const confirmed = window.confirm(
      "Cancel your PayPal subscription? Your Pro features stay active until the end of the current billing period.",
    );
    if (!confirmed) return;

    setBusy(true);
    try {
      const res = await fetch("/api/subscriptions/paypal/cancel", { method: "POST" });
      const json = (await res.json()) as { ok?: boolean; error?: string };
      if (!res.ok) throw new Error(json.error ?? "Cancel failed");
      toast.success("Subscription will end at the period close.");
      router.refresh();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Cancel failed");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Button variant="outline" onClick={cancel} disabled={busy}>
      {busy ? (
        <>
          <Loader2 className="size-4 animate-spin" /> Cancelling…
        </>
      ) : (
        "Cancel subscription"
      )}
    </Button>
  );
}
