import React from "react";
import { Controller, useFormContext } from "react-hook-form";

interface FormControllerProps {
  name: string;
  render: any;
  methods?: any;
}

// https://react-hook-form.com/api#Controller

// The controller wrapper helps with thrid party controlled components.

// The Controller can also take a prop of control, which would originally
// come from useForm. As we're using FormContext (with the FormProvider in FormTemplate)
// we can simple destructure any form methods we need here, for example setValue, etc.

export const FormController = React.memo(
  ({ name, render }: FormControllerProps) => {
    const methods = useFormContext();

    // Any errors related to current field name.
    const error = methods.formState.errors[name];

    // If field has been touched
    // const touched = methods.formState.touched[name];

    // If any of the inputs have been modified. Will use at later date if necessary.
    // const dirty = methods.formState.dirtyFields[name];

    return (
      <Controller
        name={name}
        control={methods.control}
        render={innerProps => {
          return render({
            ...innerProps, // onChange, onBlur, name, ref
            methods,
            error
          });
        }}
      />
    );
  }
);
