'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 useReactHookForm = require('../../hooks/useReactHookForm.cjs');
var FormField = require('../FormField/FormField.cjs');
var NumberInput = require('../Inputs/NumberInput/NumberInput.cjs');
var RadioGroup = require('../Inputs/RadioGroup/RadioGroup.cjs');
var Select = require('../Inputs/Select/Select.cjs');

function _interopNamespaceDefault(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__*/_interopNamespaceDefault(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 Form({
  onValid,
  onInvalid,
  fields,
  button,
  autofocus,
  mode,
  developerView,
  isDisabled,
  actions
}) {
  const filteredFields = fields.filter((field) => !field.hide);
  const initialSchemaValues = Object.fromEntries(
    filteredFields.map((field) => {
      if (field.fieldType === "select" && field.defaultValue) {
        const selectField = field;
        return [
          selectField.name,
          selectField.isMulti ? selectField.defaultValue : selectField.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 } = useReactHookForm();
  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,
    control,
    formState: { isSubmitting, errors }
  } = formMethods;
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      react$1.chakra.form,
      {
        onChange: () => setFormMethods(formMethods),
        onSubmit: handleSubmit(onValid, onInvalid),
        children: /* @__PURE__ */ jsxRuntime.jsx(react$1.chakra.fieldset, { children: /* @__PURE__ */ jsxRuntime.jsxs(react$1.VStack, { alignItems: "left", gap: 6, children: [
          fields.map(
            (_a) => {
              var _b = _a, { label, columns, help, description, footerDescription, tooltip } = _b, field = __objRest(_b, ["label", "columns", "help", "description", "footerDescription", "tooltip"]);
              var _a2;
              return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsx(
                FormField,
                {
                  description,
                  footerDescription,
                  tooltip,
                  isRequired: field.fieldType === "hidden" ? false : field.isRequired !== false,
                  isDisabled: field.isDisabled || 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,
                        pattern: field.pattern,
                        type: field.inputMode
                      }, register(field.name))
                    ),
                    toggle: /* @__PURE__ */ jsxRuntime.jsx(
                      reactHookForm.Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const toggleField = field;
                          return /* @__PURE__ */ jsxRuntime.jsx(react$1.Box, { "data-testid": `${toggleField.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(
                            react$1.Switch,
                            __spreadProps(__spreadValues({}, renderField), {
                              defaultChecked: toggleField.defaultValue === "true"
                            })
                          ) });
                        }
                      }
                    ),
                    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"]);
                          const numberField = field;
                          return /* @__PURE__ */ jsxRuntime.jsx(
                            NumberInput,
                            __spreadProps(__spreadValues({}, rest), {
                              name: numberField.name,
                              min: numberField.min,
                              max: numberField.max,
                              step: numberField.step,
                              placeholder: numberField.placeholder
                            })
                          );
                        }
                      }
                    ),
                    radio: /* @__PURE__ */ jsxRuntime.jsx(
                      reactHookForm.Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                          const radioField = field;
                          return /* @__PURE__ */ jsxRuntime.jsx(react$1.Box, { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(
                            RadioGroup,
                            __spreadProps(__spreadValues({}, rest), {
                              isAttached: radioField.isAttached,
                              options: radioField.options || [],
                              defaultValue: radioField.defaultValue,
                              onChange: (nextValue) => {
                                setValue(radioField.name, nextValue);
                                setFormMethods(formMethods);
                              }
                            })
                          ) });
                        }
                      }
                    ),
                    select: /* @__PURE__ */ jsxRuntime.jsx(
                      reactHookForm.Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                          const selectField = field;
                          return /* @__PURE__ */ jsxRuntime.jsx(react$1.Box, { "data-testid": `${selectField.name}_field`, children: /* @__PURE__ */ jsxRuntime.jsx(
                            Select.default,
                            __spreadProps(__spreadValues({}, rest), {
                              innerRef: selectField.innerRef,
                              placeholder: selectField.placeholder,
                              isMulti: selectField.isMulti,
                              options: selectField.options,
                              defaultValue: selectField.defaultValue,
                              onChange: (nextValue) => {
                                setValue(selectField.name, nextValue);
                                setFormMethods(formMethods);
                              }
                            })
                          ) });
                        }
                      }
                    ),
                    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(react$1.Box, { children: /* @__PURE__ */ jsxRuntime.jsxs(react$1.ButtonGroup, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              react$1.Button,
              {
                colorScheme: "brand",
                "aria-label": button.label,
                "data-testid": button.label,
                type: "submit",
                isLoading: isSubmitting,
                isDisabled: isSubmitting || Object.keys(errors).length > 0 || isDisabled,
                children: button.text
              }
            ),
            actions
          ] }) })
        ] }) })
      }
    ),
    developerView ? /* @__PURE__ */ jsxRuntime.jsx(devtools.DevTool, { control }) : null
  ] });
}

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