import React, { FC } from 'react'
import type { FieldRenderProps } from 'react-final-form'
import { required as requiredValidator } from 'redux-form-validators'
import { composeValidators, Field } from '../lib/Field'
import {
  TextFieldBase,
  TextFieldHTMLElement,
  TextFieldProps,
} from '../lib/TextFieldBase'

export const TextField: FC<TextFieldProps> = ({
  required,
  validate,
  ...props
}) => {
  const validators = []
  if (validate) {
    validators.push(validate)
  }
  if (required) {
    validators.push(requiredValidator())
  }
  return (
    <Field<
      any,
      FieldRenderProps<any, TextFieldHTMLElement>,
      TextFieldHTMLElement
    >
      component={
        TextFieldBase as React.ComponentType<
          FieldRenderProps<any, TextFieldHTMLElement>
        >
      }
      validate={composeValidators(validators)}
      {...props}
    />
  )
}

export default TextField
