"use client";

import { useState } from "react";

interface SubscribeButtonProps {
  escortId: number;
  isSubscribed?: boolean;
  price?: number;
  onSubscribe?: () => void;
}

export default function SubscribeButton({
  escortId,
  isSubscribed: initialSubscribed = false,
  price = 0,
  onSubscribe,
}: SubscribeButtonProps) {
  const [isSubscribed, setIsSubscribed] = useState(initialSubscribed);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubscribe = async () => {
    if (isSubscribed) return;
    setIsLoading(true);
    setError(null);

    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ escort_id: escortId }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to subscribe");
      }

      setIsSubscribed(true);
      onSubscribe?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to subscribe");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <button
        onClick={handleSubscribe}
        disabled={isLoading || isSubscribed}
        className={`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:opacity-50 ${
          isSubscribed
            ? "bg-green-600/20 text-green-400 cursor-default"
            : "bg-purple-600 text-white hover:bg-purple-700"
        }`}
      >
        {isSubscribed ? "Subscribed" : `Subscribe${price > 0 ? ` - ${price} credits` : ""}`}
      </button>
      {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
    </div>
  );
}
