import { jsx as e, jsxs as _ } from "@emotion/react/jsx-runtime";
import { forwardRef as j, useId as v } from "react";
import { useFormContext as A, Controller as M } from "react-hook-form";
import { WITH_RHF_CONTROLLER_CLASSES as O } from "./constants.js";
import T from "clsx";
import { RootStyled as W } from "./slots/WithRHFControllerSlots.js";
import { Label as $ } from "../../components/Label/Label.js";
import { HelperError as k } from "../../components/HelperError/HelperError.js";
function S(n) {
  const l = j((u, h) => {
    const {
      name: a,
      control: F,
      // Puede permitir que el componente se use fuera de un FormProvider
      label: c,
      mandatory: f,
      mandatoryMessage: C,
      helperMessage: b,
      size: r = "medium",
      disabled: g,
      id: R,
      htmlFor: N,
      ...x
    } = u, H = v(), t = R || N || H, w = A()?.control, i = F || w;
    return i ? /* @__PURE__ */ e(
      M,
      {
        name: a,
        control: i,
        render: ({ field: m, fieldState: o, formState: p }) => {
          const { value: y, onChange: I, onBlur: L, name: P } = m, s = g || p.isSubmitting, E = {
            ...x,
            value: y,
            onChange: I,
            onBlur: L,
            name: P,
            error: !!o.error,
            size: r,
            disabled: s,
            id: t,
            field: m,
            fieldState: o,
            formState: p
          };
          return /* @__PURE__ */ _(W, { ref: h, className: T(O.root), children: [
            c && /* @__PURE__ */ e(
              $,
              {
                size: r,
                label: c,
                htmlFor: t,
                mandatory: f,
                mandatoryMessage: C,
                helperMessage: b,
                disabled: s,
                error: !!o.error
              }
            ),
            /* @__PURE__ */ e(n, { ...E, ref: m.ref, size: r, disabled: s }),
            o.error?.message && /* @__PURE__ */ e(
              k,
              {
                message: o.error.message,
                size: r,
                htmlFor: t
              }
            )
          ] });
        }
      }
    ) : (console.warn(
      `withRHFController: No se encontró un control de formulario para el campo "${a}". Asegúrate de que el componente esté dentro de un FormProvider o proporciona el control como prop.`
    ), null);
  }), d = n.displayName || n.name || "Component";
  return l.displayName = `withRHFController(${d})`, l;
}
export {
  S as withRHFController
};
