import { yupResolver } from "@hookform/resolvers/yup";
import { useLayoutEffect } from "react";
import { DefaultValues, useForm, UseFormReturn } from "react-hook-form";

import { useFormStore } from "../stores/formStore";

type FormValues = { [key: string]: any }; // Dynamic type for form values

interface UseFormProps<T extends FormValues> {
  schema: any; // Yup schema for validation
  defaultValues?: T | DefaultValues<T> | undefined; // Optional default values for the form
  id: string;
}

const useAppForm = <T extends FormValues>({
  schema,
  defaultValues,
  id,
}: UseFormProps<T>): UseFormReturn<T> => {
  const { setReactHookUseForm } = useFormStore();

  const hookForm = useForm({
    // mode: "all",
    resolver: yupResolver(schema) as any, // Integrate Yup for validation
    defaultValues: defaultValues as DefaultValues<T> | undefined,
    reValidateMode: "onChange",
  });

  useLayoutEffect(() => {
    setReactHookUseForm({
      [id]: hookForm,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id, setReactHookUseForm]);

  return hookForm;
};

export default useAppForm;
