'use client';
import { useEffect, useState } from 'react';
import { useCart } from '@/contexts/CartContext';
import { fetchStockAvailability } from '@/lib/api';

interface Props {
  variantId: string;
  productId: string;
  productName: string;
  priceCents: number;
  imageUrl?: string;
  available?: boolean;
  minPurchaseQty?: number;
  /** F-138: max units available right now. Used to cap the add-to-cart action. */
  availableQuantity?: number;
  className?: string;
}

export default function AddToCartButton({
  variantId, productId, productName, priceCents, imageUrl, available = true, minPurchaseQty = 1, availableQuantity, className = '',
}: Props) {
  const { addItem, items } = useCart();
  const [added, setAdded] = useState(false);
  const [liveStock, setLiveStock] = useState<number | null>(availableQuantity ?? null);
  const qty = Math.max(1, minPurchaseQty);

  // Refresh stock so the button reflects reality (especially on stale tabs).
  useEffect(() => {
    let cancelled = false;
    fetchStockAvailability(variantId)
      .then((s) => {
        if (!cancelled) setLiveStock(s.availableQuantity);
      })
      .catch(() => {
        if (!cancelled) setLiveStock(null);
      });
    return () => {
      cancelled = true;
    };
  }, [variantId]);

  // Account for whatever the user already has in the cart for this variant.
  const inCart = items.find((it) => it.variantId === variantId)?.quantity ?? 0;
  const stockCap = liveStock ?? null;
  const remaining = stockCap === null ? null : Math.max(0, stockCap - inCart);
  const disabled = !available || (remaining !== null && remaining < qty);

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

  if (!available || remaining === 0) {
    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}
        disabled={disabled}
        className={`px-8 py-3.5 bg-[#70ad47] hover:bg-[#5a9040] text-white font-semibold rounded-xl transition-colors shadow-lg disabled:bg-gray-300 disabled:cursor-not-allowed ${className}`}
      >
        {disabled && remaining !== null ? `Solo ${remaining} uds.` : `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>
  );
}
