'use client'

import { motion } from 'framer-motion'
import MinusIcon from '@/components/icons/MinusIcon'
import PlusIcon from '@/components/icons/PlusIcon'

export interface CartQuantityControlProps {
  quantity: number
  onAdd: () => void
  onRemove: () => void
  /** در حال ارسال درخواست به سرور (نمایش اسپینر به‌جای آیکون) */
  isMutating?: boolean
  /** غیرفعال کردن دکمه افزودن (مثلاً وقتی variant انتخاب نشده) */
  addDisabled?: boolean
  /** متن دکمه وقتی quantity صفر است */
  addLabel?: string
  /** متن دکمه در حالت loading */
  addingLabel?: string
  /** عرض کامل (۱۰۰٪) */
  fullWidth?: boolean
}

const Spinner = () => (
  <span className="size-4 border-2 border-foreground/30 border-t-foreground rounded-full animate-spin block" />
)

export function CartQuantityControl({
  quantity,
  onAdd,
  onRemove,
  isMutating = false,
  addDisabled = false,
  addLabel = 'افزودن',
  addingLabel = '',
  fullWidth = false,
}: CartQuantityControlProps) {
  return (
    <motion.div
      whileTap={{ scale: 1.05 }}
      className={`bg-background active:drop-shadow-xs rounded-md h-8 inline-flex p-1 justify-between items-center gap-2 relative overflow-hidden ${fullWidth ? 'w-full' : 'max-w-[115px] w-full'}`}
    >
      {quantity <= 0 ? (
        <button
          onClick={onAdd}
          disabled={isMutating || addDisabled}
          className="inline-flex w-full justify-center items-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {isMutating ? <Spinner /> : <PlusIcon />}
          <div className="text-sm2 pt-0.5 font-normal text-foreground">
            {isMutating ? addingLabel : addLabel}
          </div>
        </button>
      ) : (
        <>
          <button
            onClick={onAdd}
            disabled={isMutating}
            className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {isMutating ? <Spinner /> : <PlusIcon className="text-foreground" />}
          </button>
          <motion.div
            key={quantity}
            initial={{ scale: 1 }}
            animate={{ scale: [1.2, 0.95, 1] }}
            transition={{ duration: 0.3 }}
            className="text-sm2 pt-0.5 font-semibold"
          >
            {quantity}
          </motion.div>
          <button
            onClick={onRemove}
            disabled={isMutating}
            className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {isMutating ? <Spinner /> : <MinusIcon className="text-foreground" />}
          </button>
        </>
      )}
    </motion.div>
  )
}
