import { DetailedHTMLProps, InputHTMLAttributes, ChangeEvent } from 'react'

type ITextInput = {
  onChange: GenericEventHandler
  label?: string
} & Omit<
  DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>,
  'onChange'
>

const TextInput = ({
  name,
  label,
  id,
  type,
  onChange,
  value,
  ...props
}: ITextInput) => {
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    if (event.target.type === 'number') {
      const newValue = {
        target: {
          type: 'custom',
          value: parseInt(event.target.value),
          name: event.target.name
        }
      }
      onChange(newValue)
    } else return onChange(event)
  }

  return (
    <>
      {label && <label htmlFor={id || name}>{label}</label>}
      <input
        id={id || name}
        name={name}
        value={value ?? ''}
        type={type}
        onChange={handleChange}
        {...props}
      />
    </>
  )
}

export default TextInput
