import {useCallback, useEffect, useState} from 'react'

import {Minus, Plus} from 'lucide-react'

import {cn} from '../../lib/utils'
import {IconButton} from '../atoms/icon-button'

interface QuantitySelectorProps {
  quantity: number
  onQuantityChange: (quantity: number) => void
  maxQuantity: number
  minQuantity?: number
  disabled?: boolean
}

export const QuantitySelector = ({
  quantity: _quantity,
  onQuantityChange,
  maxQuantity,
  minQuantity = 1,
  disabled = false,
}: QuantitySelectorProps) => {
  const [quantity, setQuantity] = useState(_quantity)

  useEffect(() => {
    setQuantity(_quantity)
  }, [_quantity])

  useEffect(() => {
    onQuantityChange(quantity)
  }, [quantity, onQuantityChange])

  const incrementDisabled = disabled || quantity >= maxQuantity
  const decrementDisabled = disabled || quantity <= minQuantity

  const incrementQuantity = useCallback(() => {
    if (incrementDisabled) return
    const newQuantity = quantity + 1 > maxQuantity ? quantity : quantity + 1
    setQuantity(newQuantity)
  }, [incrementDisabled, quantity, maxQuantity])

  const decrementQuantity = useCallback(() => {
    if (decrementDisabled) return
    const newQuantity = quantity - 1 < minQuantity ? quantity : quantity - 1
    setQuantity(newQuantity)
  }, [decrementDisabled, quantity, minQuantity])

  return (
    <>
      <div
        data-testid="QuantitySelector"
        className={cn('inline-flex w-auto bg-tertiary rounded-[8px]')}
      >
        <div
          className={cn(
            'flex h-space-32 items-center self-center overflow-hidden rounded-radius-8 bg-bg-fill-secondary',
            `p-space-8`
          )}
        >
          <IconButton
            Icon={Minus}
            onClick={decrementQuantity}
            buttonStyles="transition bg-transparent"
            filled={false}
            size="sm"
            iconStyles={cn(
              decrementDisabled ? 'text-background' : 'text-foreground',
              'stroke-3'
            )}
          />

          <div className={cn('grow', `w-[20px]`)}>
            <span className="flex items-center justify-center w-full h-full font-medium text-[10px]">
              {quantity}
            </span>
          </div>
          <IconButton
            Icon={Plus}
            onClick={incrementQuantity}
            buttonStyles="transition bg-transparent"
            filled={false}
            size="sm"
            iconStyles={cn(
              incrementDisabled ? 'text-background' : 'text-secondary',
              'stroke-3'
            )}
          />
        </div>
      </div>
    </>
  )
}
