'use strict';

var jsxRuntime = require('react/jsx-runtime');
var react = require('react');
var react$1 = require('@chakra-ui/react');
var reactHookForm = require('react-hook-form');
var devtools = require('@hookform/devtools');
var yup = require('@hookform/resolvers/yup');
var Yup = require('yup');
var useFormNext = require('../../hooks/useFormNext.cjs');
var Form = require('../Form/Form.cjs');
var FormField = require('../FormField/FormField.cjs');
var SelectNext = require('../Inputs/SelectNext/SelectNext.cjs');
var NumberInput = require('../Inputs/NumberInput/NumberInput.cjs');
var RadioGroupNext = require('../Inputs/RadioGroupNext/RadioGroupNext.cjs');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n["default"] = e;
  return Object.freeze(n);
}

var Yup__namespace = /*#__PURE__*/_interopNamespace(Yup);

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
function FormNext({
  onValid,
  onInvalid,
  fields,
  button,
  autofocus,
  mode,
  developerView,
  isDisabled
}) {
  const filteredFields = fields.filter((field) => !field.hide);
  const initialSchemaValues = Object.fromEntries(
    filteredFields.map((field) => {
      if (field.fieldType === "select" && field.defaultValue) {
        return [
          field.name,
          field.isMulti ? field.defaultValue : field.defaultValue.value
        ];
      }
      return [field.name, field.defaultValue];
    })
  );
  const schema = Object.fromEntries(filteredFields.map((field) => [field.name, field.schema]));
  const validationSchema = Yup__namespace.object().shape(schema);
  const inputRef = react.useRef();
  react.useEffect(() => {
    var _a;
    if (autofocus && inputRef)
      (_a = inputRef.current) == null ? void 0 : _a.focus();
  }, [inputRef, autofocus]);
  const { formValues, setFormMethods } = useFormNext();
  const defaultValues = formValues && Object.entries(formValues).length > 0 ? __spreadValues(__spreadValues({}, initialSchemaValues), formValues) : initialSchemaValues;
  const formMethods = reactHookForm.useForm({
    mode: mode || "all",
    defaultValues,
    resolver: yup.yupResolver(validationSchema)
  });
  react.useEffect(() => {
    setFormMethods(formMethods);
  }, []);
  const {
    register,
    handleSubmit,
    setValue,
    clearErrors,
    resetField,
    control,
    formState: { isSubmitting, errors }
  } = formMethods;
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsxs(
      Form,
      {
        onChange: () => setFormMethods(formMethods),
        onSubmit: handleSubmit(onValid, onInvalid),
        children: [
          /* @__PURE__ */ jsxRuntime.jsx(react$1.VStack, { spacing: 6, children: fields.map((_a) => {
            var _b = _a, { label, columns, help, disabled, description } = _b, field = __objRest(_b, ["label", "columns", "help", "disabled", "description"]);
            var _a2;
            return /* @__PURE__ */ jsxRuntime.jsx(
              FormField,
              {
                description,
                isDisabled: disabled || isSubmitting || isDisabled,
                hidden: field.fieldType === "hidden",
                style: columns && { gridColumn: `span ${columns}` },
                label,
                isInvalid: !!errors[field.name],
                errorText: (_a2 = errors[field.name]) == null ? void 0 : _a2.message,
                helpText: help,
                children: {
                  text: /* @__PURE__ */ jsxRuntime.jsx(
                    react$1.Input,
                    __spreadValues({
                      "data-testid": `${field.name}_field`,
                      placeholder: field.placeholder,
                      type: field.inputMode
                    }, register(field.name))
                  ),
                  toggle: /* @__PURE__ */ jsxRuntime.jsx(
                    reactHookForm.Controller,
                    {
                      name: field.name,
                      control,
                      render: ({ field: renderField }) => /* @__PURE__ */ jsxRuntime.jsx("div", { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(react$1.Switch, __spreadProps(__spreadValues({}, renderField), { defaultChecked: field.defaultValue })) })
                    }
                  ),
                  hidden: /* @__PURE__ */ jsxRuntime.jsx(
                    react$1.Input,
                    __spreadValues({
                      "data-testid": `${field.name}_field`,
                      hidden: true,
                      type: "none"
                    }, register(field.name))
                  ),
                  number: /* @__PURE__ */ jsxRuntime.jsx(
                    reactHookForm.Controller,
                    {
                      name: field.name,
                      control,
                      render: ({ field: renderField }) => {
                        const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                        return /* @__PURE__ */ jsxRuntime.jsx(
                          NumberInput,
                          __spreadProps(__spreadValues({}, rest), {
                            name: field.name,
                            min: field.min,
                            max: field.max,
                            step: field.step,
                            placeholder: field.placeholder
                          })
                        );
                      }
                    }
                  ),
                  radio: /* @__PURE__ */ jsxRuntime.jsx(
                    reactHookForm.Controller,
                    {
                      name: field.name,
                      control,
                      render: ({ field: renderField }) => {
                        const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                        return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(
                          RadioGroupNext,
                          __spreadProps(__spreadValues({}, rest), {
                            options: field.options || [],
                            defaultValue: field.defaultValue,
                            onChange: (nextValue) => {
                              setValue(field.name, nextValue);
                              setFormMethods(formMethods);
                            }
                          })
                        ) });
                      }
                    }
                  ),
                  select: /* @__PURE__ */ jsxRuntime.jsx(
                    reactHookForm.Controller,
                    {
                      name: field.name,
                      control,
                      render: ({ field: renderField }) => {
                        const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                        return /* @__PURE__ */ jsxRuntime.jsx("div", { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(
                          SelectNext,
                          __spreadProps(__spreadValues({}, rest), {
                            options: field.options || [],
                            isMulti: field.isMulti,
                            isGroup: field.isGroup,
                            max: field.max,
                            defaultValue: field.defaultValue,
                            onChange: (selectValue) => {
                              if (selectValue || selectValue === "") {
                                clearErrors(field.name);
                                const valueToSet = field.isMulti ? selectValue.map(
                                  ({ value }) => value
                                ) : selectValue.value;
                                setValue(field.name, valueToSet);
                                renderField.onChange(valueToSet);
                                setFormMethods(formMethods);
                              }
                            },
                            onReset: () => resetField(field.name)
                          })
                        ) });
                      }
                    }
                  ),
                  textarea: /* @__PURE__ */ jsxRuntime.jsx(
                    react$1.Textarea,
                    __spreadProps(__spreadValues({}, register(field.name)), {
                      "data-testid": `${field.name}_field`,
                      placeholder: field.placeholder
                    })
                  )
                }[field.fieldType || "text"]
              },
              field.name
            );
          }) }),
          /* @__PURE__ */ jsxRuntime.jsx("div", { children: /* @__PURE__ */ jsxRuntime.jsx(
            react$1.Button,
            {
              "aria-label": button.label,
              "data-testid": button.label,
              type: "submit",
              isLoading: isSubmitting,
              isDisabled: isSubmitting || Object.keys(errors).length > 0 || isDisabled,
              children: button.text
            }
          ) })
        ]
      }
    ),
    developerView ? /* @__PURE__ */ jsxRuntime.jsx(devtools.DevTool, { control }) : null
  ] });
}

module.exports = FormNext;
//# sourceMappingURL=FormNext.cjs.map
