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, className, ...props }: ITextInput) => {
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    if (event.target.type === 'number') {
      const newValue = {
        target: {
          type: 'custom',
          value: parseInt(event.target.value) ?? undefined,
          name: event.target.name,
        },
      }
      onChange(newValue)
    } else return onChange(event)
  }

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

      <style jsx>{`
        label {
          display: none;
        }
      `}</style>
    </>
  )
}

export default TextInput
