import { useState } from 'react';
import { useCartStore } from '../../stores/cart';
import { ShoppingCart } from 'lucide-react';

interface AddToCartProps {
  product: {
    id: string;
    name: string;
    price: number;
    images: string[];
    variants?: { id: string; name: string; price: number }[];
  };
  variant?: { id: string; name: string; price: number };
}

export default function AddToCart({ product, variant }: AddToCartProps) {
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);
  const [showSuccess, setShowSuccess] = useState(false);
  const addItem = useCartStore((state) => state.addItem);

  const handleAddToCart = async () => {
    setIsAdding(true);
    addItem({
      id: variant?.id || product.id,
      productId: product.id,
      name: product.name,
      price: variant?.price || product.price,
      image: product.images[0],
      variant: variant ? { id: variant.id, name: variant.name } : undefined,
      quantity
    });
    setIsAdding(false);
    setShowSuccess(true);
    setTimeout(() => setShowSuccess(false), 2000);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-4">
        <label className="text-sm font-medium">จำนวน</label>
        <div className="flex items-center border rounded-lg">
          <button
            onClick={() => setQuantity(Math.max(1, quantity - 1))}
            className="px-3 py-2 hover:bg-gray-100"
          >
            -
          </button>
          <input
            type="number"
            value={quantity}
            onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
            className="w-16 text-center border-x py-2"
          />
          <button
            onClick={() => setQuantity(quantity + 1)}
            className="px-3 py-2 hover:bg-gray-100"
          >
            +
          </button>
        </div>
      </div>
      <button
        onClick={handleAddToCart}
        disabled={isAdding}
        className={`w-full py-3 px-6 rounded-lg font-medium flex items-center justify-center gap-2 ${
          showSuccess
            ? 'bg-green-600 text-white'
            : 'bg-blue-600 text-white hover:bg-blue-700'
        }`}
      >
        <ShoppingCart className="w-5 h-5" />
        {isAdding ? 'กำลังเพิ่ม...' : showSuccess ? 'เพิ่มแล้ว!' : 'เพิ่มลงตะกร้า'}
      </button>
    </div>
  );
}
