import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { FieldValues, UseFormProps, UseFormReturn, useForm } from "react-hook-form";
import * as z4 from "zod/v4/core";

type UseHookFormProps<T extends FieldValues = FieldValues> = UseFormProps<T> & {
  resolverSchema: z4.$ZodType<T, any>;
  initialValues: UseFormProps<T>["defaultValues"];
  onDirtyChange?: (isDirty: boolean) => void;
};

export function useHookForm<T extends FieldValues = FieldValues>({
  resolverSchema,
  initialValues,
  disabled,
  onDirtyChange,
  ...rest
}: UseHookFormProps<T>): UseFormReturn<T> {
  const form = useForm<T>({
    ...rest,
    resolver: zodResolver(resolverSchema),
    defaultValues: initialValues,
    disabled,
  });

  const {
    formState: { isDirty },
  } = form;

  useEffect(() => {
    onDirtyChange?.(isDirty);
  }, [isDirty, onDirtyChange]);

  useEffect(() => {
    const applyReset = async () => {
      const values = typeof initialValues === "function" ? await initialValues() : initialValues;

      form.reset(values);
    };
    applyReset();
  }, [initialValues, form]);

  return form;
}
