import React, { useCallback } from 'react'
import { Button, Input } from 'antd'
import './styles.scss'

const inputPattern = /^\d*$/

const NumberInput = React.memo(props => {
  const { value, onChange, readOnly, max, min, className, inputClassName, ...restProps } = props
  const handleIncrease = useCallback(() => {
    if (!value || isNaN(value)) {
      onChange('1', props)
    } else {
      onChange(Math.min(max, +value + 1), props)
    }
  }, [value, onChange])

  const handleDecrease = useCallback(() => {
    if (!value || isNaN(value)) {
      onChange('1', props)
    } else {
      onChange(Math.max(min, +value - 1), props)
    }
  }, [value, onChange])

  const handleInput = useCallback(
    event => {
      const inputValue = event.target.value
      if (inputValue === '') {
        onChange('', props)
      } else if (inputPattern.test(inputValue)) {
        onChange(Math.max(Math.min(+inputValue, max), min), props)
      }
    },
    [value, onChange]
  )

  return (
    <Input.Group compact className={`lz-component-number-input ${className}`}>
      <Button onClick={handleDecrease} disabled={value <= min || readOnly} icon="minus" />
      <Input
        readOnly
        value={value}
        onChange={handleInput}
        className={inputClassName}
        {...restProps}
      />
      <Button onClick={handleIncrease} disabled={value >= max || readOnly} icon="plus" />
    </Input.Group>
  )
})

NumberInput.defaultProps = {
  max: Infinity,
  min: 0,
  className: '',
  inputClassName: '',
}

export default React.forwardRef((props, ref) => <NumberInput {...props} ref={ref} />)
