"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";

interface Props {
  highlight: boolean;
  planId: string;
  hasStripeCustomer: boolean;
}

export default function PlanButton({ highlight, planId, hasStripeCustomer }: Props) {
  const [loading, setLoading] = useState(false);

  async function handleClick() {
    setLoading(true);
    try {
      if (hasStripeCustomer) {
        // Existing Stripe customer → open billing portal to change plan
        const res = await fetch("/api/billing/portal", { method: "POST" });
        const data = await res.json();
        if (data.url) window.location.href = data.url;
      } else {
        // New subscriber → Stripe Checkout
        const res = await fetch("/api/billing/checkout", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ plan: planId }),
        });
        const data = await res.json();
        if (data.url) {
          window.location.href = data.url;
        } else {
          alert(data.error ?? "Eroare la procesarea platii. Contacteaza contact@dialpilot.com");
        }
      }
    } catch {
      alert("Eroare de conexiune. Incearca din nou.");
    }
    setLoading(false);
  }

  return (
    <button
      onClick={handleClick}
      disabled={loading}
      className={`w-full py-3 rounded-xl text-sm font-bold transition-all flex items-center justify-center gap-2 disabled:opacity-60 ${
        highlight
          ? "bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white shadow-lg shadow-indigo-500/20 hover:scale-[1.02]"
          : "border border-white/[0.12] hover:border-indigo-500/40 text-white hover:bg-white/[0.05]"
      }`}
    >
      {loading && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
      {loading ? "Se redirectioneaza..." : hasStripeCustomer ? "Gestioneaza abonamentul" : "Incepe acum"}
    </button>
  );
}
