"use client";

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

declare global {
  interface Window {
    Stripe: any;
  }
}

export function UpgradeButton({ isPremium }: { isPremium: boolean }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleUpgrade() {
    setError(null);
    setLoading(true);

    try {
      // Load Stripe from CDN
      if (!window.Stripe) {
        const script = document.createElement("script");
        script.src = "https://js.stripe.com/v3/";
        script.onload = () => {
          // Continue after script loads
        };
        document.head.appendChild(script);
        // Wait for script to load
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }

      const res = await fetch("/api/stripe/create-checkout", {
        method: "POST",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create checkout");

      const stripe = window.Stripe(process.env.NEXT_PUBLIC_STRIPE_KEY || "");
      if (!stripe) throw new Error("Stripe failed to load");

      const { error } = await stripe.redirectToCheckout({
        sessionId: data.sessionId,
      });
      if (error) throw new Error(error.message);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  }

  if (isPremium) {
    return (
      <span className="inline-flex items-center gap-1 rounded-full bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-700">
        <Crown className="h-4 w-4" />
        Premium
      </span>
    );
  }

  return (
    <div className="space-y-2">
      <button
        onClick={handleUpgrade}
        disabled={loading}
        className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-teal-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-teal-700 disabled:opacity-60"
      >
        {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
        Passer à Premium
      </button>
      {error && (
        <p className="text-xs text-rose-600">{error}</p>
      )}
    </div>
  );
}
