"use client";
import { ForwardedRef, useImperativeHandle } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import useReportStepValidity from "./useReportStepValidity";

export interface IContactsStepFields {
  title: string;
  description: string;
  submit_button_text: string;
  fields: {
    name: string;
    label: string;
    placeholder: string;
    required: boolean;
  }[];
}

const useContactsStepPresenter = (
  initialData?: IContactsStepFields,
  ref?: ForwardedRef<unknown>,
  onValidityChange?: (valid: boolean) => void,
) => {
  const {
    register,
    handleSubmit,
    control,
    getValues,
    formState: { errors, isValid },
    trigger,
  } = useForm<IContactsStepFields>({
    mode: "onChange",
    defaultValues: initialData || {
      fields: [
        {
          name: "first_name",
          label: "",
          placeholder: "",
          required: false,
        },
        {
          name: "last_name",
          label: "",
          placeholder: "",
          required: false,
        },
        { name: "email", label: "", placeholder: "", required: false },
        { name: "phone", label: "", placeholder: "", required: false },
      ],
    },
  });

  const { fields } = useFieldArray({
    control,
    name: "fields",
  });

  useReportStepValidity(isValid, onValidityChange);

  const onSubmit = (data: IContactsStepFields) => {
    console.log(data);
  };

  useImperativeHandle(ref, () => ({
    getData: () => getValues(),
    validate: () => trigger(),
  }));

  return {
    register,
    handleSubmit,
    errors,
    onSubmit,
    fields,
    control,
  };
};

export default useContactsStepPresenter;
