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

export interface IChartStepFields {
  title: string;
  missed_amount: string;
  data: { key: string; value: number }[];
}

const useChartStepPresenter = (
  initialData?: IChartStepFields,
  ref?: ForwardedRef<unknown>,
  onValidityChange?: (valid: boolean) => void,
) => {
  const {
    register,
    handleSubmit,
    control,
    watch,
    formState: { errors, isValid },
    getValues,
    trigger,
  } = useForm<IChartStepFields>({
    defaultValues: initialData || {
      data: [{ key: "", value: 0 }],
    },
    mode: "onChange",
  });

  useReportStepValidity(isValid, onValidityChange);

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

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

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

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

export default useChartStepPresenter;
