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

export interface IFeaturesStepFields {
  title: string;
  description: string;
  cards: {
    icon: string;
    title: string;
    description: string;
  }[];
}

const useFeaturesStepPresenter = (
  initialData?: IFeaturesStepFields,
  ref?: ForwardedRef<unknown>,
  onValidityChange?: (valid: boolean) => void,
) => {
  const {
    register,
    handleSubmit,
    control,
    watch,
    formState: { errors, isValid },
    getValues,
    trigger,
  } = useForm<IFeaturesStepFields>({
    defaultValues: initialData || {
      cards: [{ icon: "", title: "", description: "" }],
    },
    mode: "onChange",
  });

  useReportStepValidity(isValid, onValidityChange);

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

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

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

  return {
    register,
    handleSubmit,
    errors,
    onSubmit,
    fields,
    append,
    remove,
    control,
    watch,
  };
};

export default useFeaturesStepPresenter;
