"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { cartStore } from "@/lib/cart"

interface Product {
  id: string
  name: string
  price: number
  sizes: string[]
  images: string[]
}

interface Props {
  product: Product
}

export function AddToCartButton({ product }: Props) {
  const [selectedSize, setSelectedSize] = useState<string>("")
  const [error, setError] = useState("")
  const [added, setAdded] = useState(false)

  function handleAddToCart() {
    if (!selectedSize) {
      setError("Sélectionne une taille")
      return
    }
    setError("")
    cartStore.add({
      id: product.id,
      name: product.name,
      price: product.price,
      size: selectedSize,
      image: product.images[0] ?? "",
    })
    setAdded(true)
    setTimeout(() => setAdded(false), 2000)
  }

  return (
    <div className="space-y-4">
      {/* Sizes */}
      <div>
        <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-3">
          Taille
        </p>
        <div className="flex flex-wrap gap-2">
          {product.sizes.map((size) => (
            <button
              key={size}
              onClick={() => { setSelectedSize(size); setError("") }}
              className={`h-10 min-w-[2.5rem] px-3 border font-mono text-xs uppercase tracking-widest transition-colors cursor-pointer ${
                selectedSize === size
                  ? "border-[var(--accent)] bg-[var(--accent)] text-white"
                  : "border-[var(--border)] text-[var(--text-secondary)] hover:border-[var(--border-subtle)] hover:text-[var(--text)]"
              }`}
            >
              {size}
            </button>
          ))}
        </div>
        {error && (
          <p className="mt-2 text-xs text-red-500 font-mono">{error}</p>
        )}
      </div>

      <Button onClick={handleAddToCart} size="xl" className="w-full">
        {added ? "✓ Ajouté au panier" : "Ajouter au panier"}
      </Button>
    </div>
  )
}
