import React, { Fragment } from 'react';
import { Field as FinalField } from 'react-final-form';
import { Input } from './index';
import { InputProps } from '../../types';
import { ErrorMessage } from '../ErrorMessage';

export interface IFormProps extends InputProps {
  name: string;
  onClear?: (val: string) => void;
  required?: boolean;
  type?: string;
}

export const FormInput = ({
  onClear = (val: string) => {},
  type = 'string',
  ...props
}: IFormProps & React.InputHTMLAttributes<HTMLInputElement>) => {
  const clear = () => onClear(props.name);
  return (
    <FinalField
      name={props.name}
      validate={(val) => {
        if (props.required) {
          if (!val) {
            let errors = {};
            errors[props.name] = 'required';
            return errors;
          }
        }
        return undefined;
      }}
      displayEmpty
    >
      {({ input, meta }) => {
        const newProps = { ...props };

        return (
          <Fragment>
            <Input
              type={type}
              {...input}
              {...newProps}
              error={meta.error && meta.error[props.name]}
              clear={clear}
            />
          </Fragment>
        );
      }}
    </FinalField>
  );
};
