import React from "react";
import { Controller, Control, FieldPath, FieldValues } from "react-hook-form";
import { FormGroup } from "../core/form/form-groups";

interface ReformControllerProps<
  TFieldValues extends FieldValues = FieldValues
> {
  index: number;
  field: string;
  control: Control<TFieldValues>;
  render: (props: {
    field: any;
    fieldState: any;
    formState: any;
  }) => React.ReactElement;
  rules?: any;
  defaultValue?: any;
  shouldUnregister?: boolean;
  name?: never;
}

export const ReformController = <
  TFieldValues extends { groups: Array<FormGroup<any>> } = {
    groups: Array<FormGroup<any>>;
  }
>({
  index,
  field,
  control,
  render,
  rules,
  defaultValue,
  shouldUnregister,
}: ReformControllerProps<TFieldValues>) => {
  const name = `groups.${index}.data.${field}` as FieldPath<TFieldValues>;

  return (
    <Controller
      name={name}
      control={control}
      rules={rules}
      defaultValue={defaultValue}
      shouldUnregister={shouldUnregister}
      render={render}
    />
  );
};
