"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { Form } from '../form.mjs';
import React__default from 'react';
import { useForm } from 'react-hook-form';
import '../button.mjs';
import { cn } from '../../lib/utils.mjs';
import { zodResolver } from '@hookform/resolvers/zod';
import AutoFormObject from './fields/object.mjs';
import { getObjectFormSchema, getDefaultValues } from './helpers.mjs';

function AutoForm({
  formSchema,
  values: valuesProp,
  onValuesChange: onValuesChangeProp,
  onParsedValuesChange,
  onSubmit: onSubmitProp,
  fieldConfig,
  children,
  className,
  dependencies
}) {
  const objectFormSchema = getObjectFormSchema(formSchema);
  const defaultValues = getDefaultValues(objectFormSchema, fieldConfig);
  const form = useForm({
    // Cast to any to handle Zod v4 type compatibility with @hookform/resolvers
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues ?? void 0,
    values: valuesProp
  });
  function onSubmit(values) {
    const parsedValues = formSchema.safeParse(values);
    if (parsedValues.success) {
      onSubmitProp?.(parsedValues.data, form);
    }
  }
  React__default.useEffect(() => {
    const subscription = form.watch((values) => {
      onValuesChangeProp?.(values, form);
      const parsedValues = formSchema.safeParse(values);
      if (parsedValues.success) {
        onParsedValuesChange?.(parsedValues.data, form);
      }
    });
    return () => subscription.unsubscribe();
  }, [form, formSchema, onValuesChangeProp, onParsedValuesChange]);
  const renderChildren = typeof children === "function" ? children(form.formState) : children;
  return /* @__PURE__ */ jsx("div", { className: "w-full", children: /* @__PURE__ */ jsx(Form, { ...form, children: /* @__PURE__ */ jsxs(
    "form",
    {
      onSubmit: (e) => {
        form.handleSubmit(onSubmit)(e);
      },
      className: cn("space-y-5", className),
      children: [
        /* @__PURE__ */ jsx(
          AutoFormObject,
          {
            schema: objectFormSchema,
            form,
            dependencies,
            fieldConfig
          }
        ),
        renderChildren
      ]
    }
  ) }) });
}

export { AutoForm as default };
