'use client';
import { useState } from 'react';
import { useCart } from '@/contexts/CartContext';

interface Props {
  variantId: string;
  productId: string;
  productName: string;
  priceCents: number;
  imageUrl?: string;
  available?: boolean;
  minPurchaseQty?: number;
  className?: string;
}

export default function AddToCartButton({
  variantId, productId, productName, priceCents, imageUrl, available = true, minPurchaseQty = 1, className = '',
}: Props) {
  const { addItem, itemCount } = useCart();
  const [added, setAdded] = useState(false);
  const qty = Math.max(1, minPurchaseQty);

  const handleAdd = () => {
    if (!available) return;
    addItem({ variantId, productId, productName, quantity: qty, priceCents, imageUrl, minPurchaseQty: qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 2000);
  };

  if (!available) {
    return (
      <button disabled className={`px-8 py-3.5 bg-gray-200 text-gray-500 font-semibold rounded-xl cursor-not-allowed ${className}`}>
        Agotado
      </button>
    );
  }

  if (added) {
    return (
      <button disabled className={`px-8 py-3.5 bg-[#52B788] text-white font-semibold rounded-xl cursor-default ${className}`}>
        ✓ Añadido
      </button>
    );
  }

  return (
    <div>
      <button
        onClick={handleAdd}
        className={`px-8 py-3.5 bg-[#70ad47] hover:bg-[#5a9040] text-white font-semibold rounded-xl transition-colors shadow-lg ${className}`}
      >
        Añadir al carrito{qty > 1 ? ` (${qty} uds.)` : ''}
      </button>
      {qty > 1 && (
        <p className="mt-2 text-xs text-gray-500">Compra mínima: {qty} unidades.</p>
      )}
    </div>
  );
}
