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<TFields extends FieldValues = FieldValues, TContext = any> = UseFormProps<
  TFields,
  TContext
> & {
  resolverSchema: z4.$ZodType<TFields, any>;
  initialValues: UseFormProps<TFields>["defaultValues"];
  onDirtyChange?: (isDirty: boolean) => void;
};

export function useHookForm<TFields extends FieldValues = FieldValues, TContext = any>({
  resolverSchema,
  initialValues,
  disabled,
  onDirtyChange,
  ...rest
}: UseHookFormProps<TFields, TContext>): UseFormReturn<TFields> {
  const form = useForm<TFields, TContext>({
    ...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;
}
