import React, { FC } from 'react'
import type { FieldRenderProps } from 'react-final-form'
import { required as requiredValidator } from 'redux-form-validators'
import { composeValidators, Field, FieldProps } from '../lib/Field'
import {
  ISelectStandardProps,
  SelectFieldBase,
  SelectHTMLElement,
} from '../lib/SelectFieldBase'

export interface ISelectProps
  extends ISelectStandardProps,
    FieldProps<SelectHTMLElement> {}

export const SelectField: FC<ISelectProps> = ({
  children,
  required,
  validate,
  formControlProps = {},
  ...props
}) => {
  const render = (renderProps: FieldRenderProps<any, SelectHTMLElement>) => (
    <SelectFieldBase
      {...renderProps}
      {...props}
      formControlProps={{ ...formControlProps, required }}
    >
      {children}
    </SelectFieldBase>
  )
  const validators = []
  if (validate) {
    validators.push(validate)
  }
  if (required) {
    validators.push(requiredValidator())
  }

  return (
    <Field<any, FieldRenderProps<any, SelectHTMLElement>, SelectHTMLElement>
      render={render}
      validate={composeValidators(validators)}
      {...props}
    />
  )
}
SelectField.defaultProps = {
  formControlProps: {
    fullWidth: true,
  },
}
export default SelectField
