'use client';

import { useState } from 'react';
import { useCart } from '@/lib/cart-context';

export function ProductQuantityAddToCart({
  productId,
  slug,
  name,
  price,
  image,
}: {
  productId: number;
  slug: string;
  name: string;
  price: number;
  image: string;
}) {
  const { addItem } = useCart();
  const [quantity, setQuantity] = useState(1);
  const [added, setAdded] = useState(false);

  function handleAdd() {
    addItem({ productId, slug, name, price, image }, quantity);
    setAdded(true);
    setTimeout(() => setAdded(false), 1500);
  }

  return (
    <div className="mt-6 flex flex-wrap items-center gap-4">
      <div className="flex items-center rounded-md border border-navy-100">
        <button
          type="button"
          aria-label="Decrease quantity"
          onClick={() => setQuantity((q) => Math.max(1, q - 1))}
          className="flex h-10 w-10 items-center justify-center text-navy-800 hover:bg-beige"
        >
          &#8722;
        </button>
        <span className="flex h-10 w-12 items-center justify-center border-x border-navy-100 text-sm font-medium text-navy-800">
          {quantity}
        </span>
        <button
          type="button"
          aria-label="Increase quantity"
          onClick={() => setQuantity((q) => q + 1)}
          className="flex h-10 w-10 items-center justify-center text-navy-800 hover:bg-beige"
        >
          +
        </button>
      </div>
      <button type="button" onClick={handleAdd} className="btn-primary">
        {added ? 'Added ✓' : 'Add to Cart'}
      </button>
    </div>
  );
}
