'use client'

import { useState } from 'react'
import * as motion from 'framer-motion/m'
import { AnimatePresence, type Variants } from 'framer-motion'
import { useTranslations } from 'next-intl'
import { Minus, Plus } from 'lucide-react'

const slideVariants: Variants = {
  enter: (dir: number) => ({ y: dir * 16, opacity: 0 }),
  center: { y: 0, opacity: 1 },
  exit: (dir: number) => ({ y: -dir * 16, opacity: 0 }),
}

interface ProductQuantityProps {
  quantity: number
  onQuantityChange: (quantity: number) => void
  min?: number
  max?: number
  stock?: number
}

export default function ProductQuantity({
  quantity,
  onQuantityChange,
  min = 1,
  max = 99,
  stock = 100
}: ProductQuantityProps) {
  // Which way the number should slide — a ref would be simpler, but reading
  // ref.current during render is disallowed (react-hooks/refs); state, set
  // in these click handlers (not an effect), is the correct tool here.
  const [direction, setDirection] = useState<1 | -1>(1)
  const t = useTranslations('ProductDetail')

  const decrease = () => {
    if (quantity > min) {
      setDirection(-1)
      onQuantityChange(quantity - 1)
    }
  }

  const increase = () => {
    if (quantity < Math.min(max, stock)) {
      setDirection(1)
      onQuantityChange(quantity + 1)
    }
  }

  return (
    <div className="flex items-center gap-3">
      <span className="text-dark font-medium">{t('quantity')}</span>
      <div className="flex items-center border border-gray-200 rounded-lg">
        <button
          onClick={decrease}
          disabled={quantity <= min}
          className={`p-2 px-3 rounded-l-lg transition-colors ${
            quantity <= min
              ? 'text-gray-300 cursor-not-allowed'
              : 'hover:bg-gray-50 text-dark'
          }`}
        >
          <Minus size={16} />
        </button>
        <span className="w-12 h-9 flex items-center justify-center overflow-hidden relative">
          <AnimatePresence mode="popLayout" initial={false} custom={direction}>
            <motion.span
              key={quantity}
              custom={direction}
              variants={slideVariants}
              initial="enter"
              animate="center"
              exit="exit"
              transition={{ duration: 0.18 }}
              className="text-dark font-medium absolute"
            >
              {quantity}
            </motion.span>
          </AnimatePresence>
        </span>
        <button
          onClick={increase}
          disabled={quantity >= Math.min(max, stock)}
          className={`p-2 px-3 rounded-r-lg transition-colors ${
            quantity >= Math.min(max, stock)
              ? 'text-gray-300 cursor-not-allowed'
              : 'hover:bg-gray-50 text-dark'
          }`}
        >
          <Plus size={16} />
        </button>
      </div>
      <span className="text-sm text-gray-custom">{t('itemsInStock', { stock })}</span>
    </div>
  )
}
