"use client";

import { useState } from "react";

interface PurchaseUnlockButtonProps {
  contentType: "gallery" | "video" | "blog" | "erotica";
  contentId: number;
  price: number;
  isPurchased?: boolean;
  onPurchase?: () => void;
}

export default function PurchaseUnlockButton({
  contentType,
  contentId,
  price,
  isPurchased: initialPurchased = false,
  onPurchase,
}: PurchaseUnlockButtonProps) {
  const [isPurchased, setIsPurchased] = useState(initialPurchased);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handlePurchase = async () => {
    if (isPurchased) return;
    setIsLoading(true);
    setError(null);

    try {
      const res = await fetch(`/api/purchases/${contentType}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [`${contentType}_id`]: contentId }),
      });

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

      setIsPurchased(true);
      onPurchase?.();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Purchase failed");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <button
        onClick={handlePurchase}
        disabled={isLoading || isPurchased}
        className={`inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:opacity-50 ${
          isPurchased
            ? "bg-green-600/20 text-green-400 cursor-default"
            : "bg-amber-600 text-white hover:bg-amber-700"
        }`}
      >
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d={isPurchased ? "M5 13l4 4L19 7" : "M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"}
          />
        </svg>
        {isPurchased ? "Unlocked" : `Unlock - ${price} credits`}
      </button>
      {error && <p className="mt-1 text-xs text-red-400">{error}</p>}
    </div>
  );
}
