import React from 'react';
import { useFormState, useForm, Control } from 'react-hook-form';

let renderCounter = 0;

type FormInputs = {
  firstName: string;
  lastName: string;
  min: string;
  max: string;
  minDate: string;
  maxDate: string;
  minLength: string;
  minRequiredLength: string;
  selectNumber: string;
  pattern: string;
  nestItem: {
    nest1: string;
  };
  arrayItem: {
    test1: string;
  }[];
};

const SubForm = ({ control }: { control: Control<FormInputs> }) => {
  const {
    isDirty,
    dirtyFields,
    touchedFields,
    isSubmitted,
    isSubmitSuccessful,
    submitCount,
    isValid,
  } = useFormState({
    control,
  });

  return (
    <p id="state">
      {JSON.stringify({
        isDirty,
        touched: Object.keys(touchedFields),
        dirty: Object.keys(dirtyFields),
        isSubmitted,
        isSubmitSuccessful,
        submitCount,
        isValid,
      })}
    </p>
  );
};

export const UseFormState: React.FC = () => {
  const { register, handleSubmit, control, reset } = useForm<FormInputs>({
    mode: 'onChange',
  });
  const onValid = () => {};

  renderCounter++;

  return (
    <form onSubmit={handleSubmit(onValid)}>
      <input
        placeholder="nest.nest1"
        {...register('nestItem.nest1', { required: true })}
      />
      <input
        placeholder="arrayItem.0.test1"
        {...register('arrayItem.0.test1', { required: true })}
      />
      <input
        {...register('firstName', { required: true })}
        placeholder="firstName"
      />
      <input
        {...register('lastName', { required: true, maxLength: 5 })}
        placeholder="lastName"
      />
      <input
        type="number"
        {...register('min', { min: 10 })}
        placeholder="min"
      />
      <input
        type="number"
        {...register('max', { max: 20 })}
        placeholder="max"
      />
      <input
        type="date"
        {...register('minDate', { min: '2019-08-01' })}
        placeholder="minDate"
      />
      <input
        type="date"
        {...register('maxDate', { max: '2019-08-01' })}
        placeholder="maxDate"
      />
      <input
        {...register('minLength', { minLength: 2 })}
        placeholder="minLength"
      />
      <input
        {...register('minRequiredLength', { minLength: 2, required: true })}
        placeholder="minRequiredLength"
      />
      <select {...register('selectNumber', { required: true })}>
        <option value="">Select</option>
        <option value={1}>1</option>
        <option value={2}>1</option>
      </select>
      <input
        {...register('pattern', { pattern: /\d+/ })}
        placeholder="pattern"
      />
      <button id="submit">Submit</button>
      <button type="button" id="resetForm" onClick={() => reset()}>
        Reset
      </button>
      <div id="renderCount">{renderCounter}</div>
      <SubForm control={control} />
    </form>
  );
};
