import React, { Fragment, useState } from 'react';
import { Field as FinalField } from 'react-final-form';
import { TimeInput, IProps } from './index';
import { ErrorMessage } from '../ErrorMessage';
import { isPropertyAccessOrQualifiedName } from 'typescript';

export interface IFormProps extends IProps {
  name: string;
  onClear?: (val: string) => void;
  required?: boolean;
  setValue?: (val1: string, val2: string) => void;
}

export const FormTimeInput = ({
  ...props
}: IFormProps & React.InputHTMLAttributes<HTMLInputElement>) => {
  // const [value, setValue] = useState<string>('');
  const clear = () => props.onClear(props.name);
  const onChange = (val: string) => {
    // setValue(val);
    if (props.setValue) {
      props.setValue(props.name, val);
    }
  };
  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 };
        if (newProps.onClear) {
          //@ts-ignore
          delete newProps?.onClear;
        }

        return (
          <Fragment>
            <TimeInput
              onChange={onChange}
              label={props.label}
              sizer={props.sizer}
              noLabel={props.noLabel}
              {...input}
              {...props}
            />
          </Fragment>
        );
      }}
    </FinalField>
  );
};
