import React, { useState, useEffect } from 'react'
import { Minus, Plus } from 'lucide-react'
import { Button } from '@/components/shadcn/ui/button'

interface CounterProps {
  /**
   * Initial value for the counter
   * @default 0
   */
  initialValue?: number

  /**
   * Minimum allowed value
   * @default 0
   */
  min?: number

  /**
   * Maximum allowed value
   * @default Infinity
   */
  max?: number

  /**
   * Step to increment/decrement by
   * @default 1
   */
  step?: number

  /**
   * Callback function that gets called when the counter value changes
   */
  onChange?: (value: number) => void

  /**
   * Optional CSS class to style the counter container
   */
  className?: string

  /**
   * Whether the counter is disabled
   * @default false
   */
  disabled?: boolean
}

/**
 * A counter component that allows incrementing and decrementing a value
 * and exposes the current value to parent components through the onChange callback.
 */
const Counter: React.FC<CounterProps> = ({
  initialValue = 0,
  min = 0,
  max = Infinity,
  step = 1,
  onChange,
  className = '',
  disabled = false,
}) => {
  const [value, setValue] = useState<number>(
    Math.max(min, Math.min(initialValue, max)),
  )

  useEffect(() => {
    // Call onChange when the component mounts to ensure parent components
    // have the initial value
    if (onChange) {
      onChange(value)
    }
  }, [])

  const increment = () => {
    if (disabled) return

    const newValue = Math.min(value + step, max)
    if (newValue !== value) {
      setValue(newValue)
      if (onChange) {
        onChange(newValue)
      }
    }
  }

  const decrement = () => {
    if (disabled) return

    const newValue = Math.max(value - step, min)
    if (newValue !== value) {
      setValue(newValue)
      if (onChange) {
        onChange(newValue)
      }
    }
  }

  return (
    <div className={`flex items-center ${className}`}>
      <Button
        type="button"
        variant="secondary"
        size="icon"
        onClick={decrement}
        disabled={disabled || value <= min}
        className="rounded-r-none h-10 w-10 sm:h-12 sm:w-12"
        aria-label="Decrease"
      >
        <Minus className="h-4 w-4" />
      </Button>

      <div className="flex items-center justify-center h-10 sm:h-12 flex-1 border border-x-0 border-input">
        <span className="text-sm font-medium">{value}</span>
      </div>

      <Button
        type="button"
        variant="secondary"
        size="icon"
        onClick={increment}
        disabled={disabled || value >= max}
        className="rounded-l-none h-10 w-10 sm:h-12 sm:w-12"
        aria-label="Increase"
      >
        <Plus className="h-4 w-4" />
      </Button>
    </div>
  )
}

export default Counter
