import React from 'react';
import { useForm, ValidationMode } from 'react-hook-form';
import { useParams } from 'react-router-dom';

let renderCounter = 0;

const FormStateWithNestedFields = () => {
  const { mode } = useParams();
  const {
    register,
    handleSubmit,
    formState: {
      dirtyFields,
      isSubmitted,
      submitCount,
      touchedFields,
      isDirty,
      isSubmitting,
      isSubmitSuccessful,
      isValid,
    },
    reset,
  } = useForm<{
    left: {
      test1: string;
      test2: string;
    };
    right: {
      test1: string;
      test2: string;
    };
  }>({
    mode: mode as keyof ValidationMode,
    defaultValues: {
      left: {
        test1: '',
        test2: '',
      },
      right: {
        test1: '',
        test2: '',
      },
    },
  });

  renderCounter++;

  return (
    <form onSubmit={handleSubmit(() => {})}>
      <div style={{ display: 'flex' }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <h4>Left</h4>
          <input
            {...register('left.test1', { required: true })}
            placeholder="firstName"
          />
          <input
            {...register('left.test2', { required: true })}
            placeholder="lastName"
          />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <h4>Right</h4>
          <input
            {...register('right.test1', { required: false })}
            placeholder="firstName"
          />
          <input
            {...register('right.test2', { required: false })}
            placeholder="lastName"
          />
        </div>
      </div>
      <div id="state">
        {JSON.stringify({
          isDirty,
          isSubmitted,
          submitCount,
          isSubmitting,
          isSubmitSuccessful,
          isValid,
          touched: (
            Object.keys(touchedFields) as Array<keyof typeof touchedFields>
          ).flatMap((topLevelKey) =>
            Object.keys(touchedFields[topLevelKey] || {}).map(
              (nestedKey) => `${topLevelKey}.${nestedKey}`,
            ),
          ),
          dirty: (
            Object.keys(dirtyFields) as Array<keyof typeof touchedFields>
          ).flatMap((topLevelKey) =>
            Object.keys(dirtyFields[topLevelKey] || {}).map(
              (nestedKey) => `${topLevelKey}.${nestedKey}`,
            ),
          ),
        })}
      </div>
      <button id="submit">Submit</button>
      <button type="button" onClick={() => reset()} id="resetForm">
        Reset
      </button>
      <div id="renderCount">{renderCounter}</div>
    </form>
  );
};

export default FormStateWithNestedFields;
