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

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

export const FormDateInput = ({
  onClear = (val: string) => {},
  ...props
}: IFormProps) => {
  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>
            <DateInput
              {...props}
              {...input}
              error={meta.error && meta.error[props.name]}
              clear={clear}
            />
          </Fragment>
        );
      }}
    </FinalField>
  );
};
