import { useTranslation } from 'react-i18next'

interface Props {
  value: number
  min?: number
  max?: number
  onChange: (value: number) => void
  className?: string
  style?: React.CSSProperties
  'aria-label'?: string
}

export default function NumberInput({ value, min = 0, max = 999, onChange, className, style, 'aria-label': ariaLabel }: Props) {
  const { t } = useTranslation()
  const clamp = (n: number) => Math.min(max, Math.max(min, n))

  const onKeyDown = (e: React.KeyboardEvent) => {
    let next: number | null = null
    if (e.key === 'ArrowUp') next = value + 1
    else if (e.key === 'ArrowDown') next = value - 1
    else if (e.key === 'PageUp') next = value + 10
    else if (e.key === 'PageDown') next = value - 10
    else if (e.key === 'Home') next = min
    else if (e.key === 'End') next = max
    if (next === null) return
    e.preventDefault()
    onChange(clamp(next))
  }

  return (
    <div className={`cv-number ${className || ''}`} style={style}
      role="spinbutton" aria-valuenow={value} aria-valuemin={min} aria-valuemax={max}
      aria-label={ariaLabel} tabIndex={0} onKeyDown={onKeyDown}>
      <button className="cv-number-btn" onClick={() => onChange(clamp(value - 1))} type="button" disabled={value <= min}
        aria-label={t('ui.decrease')} tabIndex={-1}>-</button>
      <span className="cv-number-value" aria-hidden="true">{value}</span>
      <button className="cv-number-btn" onClick={() => onChange(clamp(value + 1))} type="button" disabled={value >= max}
        aria-label={t('ui.increase')} tabIndex={-1}>+</button>
    </div>
  )
}