'use client'

import { ShoppingCart, Plus, Minus, Check } from 'lucide-react'
import { useCatalogStore } from '@/lib/store'
import { useState, memo } from 'react'

/**
 * MiniCartButton — small inline cart control shown on every product card/row.
 *
 * Three states:
 *  - idle (not in cart): single amber "+ Carrinho" button
 *  - in cart: stepper with [−] qty [+], qty in the middle, click label opens cart
 *  - just-added: brief "Adicionado!" feedback (1.2s)
 *
 * The whole control is self-contained and memoized so adding to cart on one
 * card doesn't re-render every other card.
 */
export const MiniCartButton = memo(function MiniCartButton({
  code,
  size = 'sm',
}: {
  code: string
  size?: 'sm' | 'md'
}) {
  const cart = useCatalogStore(s => s.cart)
  const addToCart = useCatalogStore(s => s.addToCart)
  const incrementCart = useCatalogStore(s => s.incrementCart)
  const decrementCart = useCatalogStore(s => s.decrementCart)
  const setCartOpen = useCatalogStore(s => s.setCartOpen)

  const [justAdded, setJustAdded] = useState(false)
  const item = cart.find(i => i.code === code)
  const inCart = !!item

  const handleAdd = (e: React.MouseEvent) => {
    e.stopPropagation()
    addToCart(code, 1)
    setJustAdded(true)
    setTimeout(() => setJustAdded(false), 1200)
  }

  const handleInc = (e: React.MouseEvent) => {
    e.stopPropagation()
    incrementCart(code)
  }
  const handleDec = (e: React.MouseEvent) => {
    e.stopPropagation()
    decrementCart(code)
  }
  const openCart = (e: React.MouseEvent) => {
    e.stopPropagation()
    setCartOpen(true)
  }

  // Sizing
  const btn = size === 'sm'
    ? 'h-8 px-2.5 text-[11px] gap-1'
    : 'h-10 px-4 text-sm gap-1.5'
  const stepBtn = size === 'sm' ? 'w-7 h-7' : 'w-9 h-9'
  const stepIcon = size === 'sm' ? 'w-3.5 h-3.5' : 'w-4 h-4'
  const qtyText = size === 'sm' ? 'text-xs' : 'text-sm'

  if (justAdded && !inCart) {
    // brief success flash before the stepper appears
    return (
      <div className={`inline-flex items-center justify-center rounded-full bg-green-500 text-white font-semibold ${btn}`}>
        <Check className={stepIcon} /> Adicionado
      </div>
    )
  }

  if (!inCart) {
    return (
      <button
        onClick={handleAdd}
        className={`inline-flex items-center justify-center rounded-full bg-amber-400 text-black font-semibold hover:bg-amber-500 active:scale-95 transition-all ${btn}`}
      >
        <ShoppingCart className={stepIcon} />
        {size === 'sm' ? 'Adicionar' : 'Adicionar ao carrinho'}
      </button>
    )
  }

  // In cart — stepper with qty
  return (
    <div className={`inline-flex items-center rounded-full bg-amber-50 border border-amber-200 overflow-hidden`}>
      <button
        onClick={handleDec}
        className={`${stepBtn} flex items-center justify-center text-amber-700 hover:bg-amber-100 transition-colors flex-shrink-0`}
        aria-label="Diminuir quantidade"
      >
        <Minus className={stepIcon} />
      </button>
      <button
        onClick={openCart}
        className={`min-w-[28px] ${qtyText} font-bold text-amber-900 hover:underline px-1 flex items-center gap-1`}
        title="Ver carrinho"
      >
        {item!.qty}
        <ShoppingCart className="w-3 h-3 opacity-70" />
      </button>
      <button
        onClick={handleInc}
        className={`${stepBtn} flex items-center justify-center text-amber-700 hover:bg-amber-100 transition-colors flex-shrink-0`}
        aria-label="Aumentar quantidade"
      >
        <Plus className={stepIcon} />
      </button>
    </div>
  )
})
