import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useRef, useEffect } from 'react';
import { chakra, VStack, Input, Box, Switch, Textarea, ButtonGroup, Button } from '@chakra-ui/react';
import { useForm, Controller } from 'react-hook-form';
import { DevTool } from '@hookform/devtools';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';
import useReactHookForm from '../../hooks/useReactHookForm.js';
import FormField from '../FormField/FormField.js';
import NumberInput from '../Inputs/NumberInput/NumberInput.js';
import RadioGroup from '../Inputs/RadioGroup/RadioGroup.js';
import Select from '../Inputs/Select/Select.js';

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.object().shape(schema);
  const inputRef = useRef();
  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 = useForm({
    mode: mode || "all",
    defaultValues,
    resolver: yupResolver(validationSchema)
  });
  useEffect(() => {
    setFormMethods(formMethods);
  }, []);
  const {
    register,
    handleSubmit,
    setValue,
    control,
    formState: { isSubmitting, errors }
  } = formMethods;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      chakra.form,
      {
        onChange: () => setFormMethods(formMethods),
        onSubmit: handleSubmit(onValid, onInvalid),
        children: /* @__PURE__ */ jsx(chakra.fieldset, { children: /* @__PURE__ */ jsxs(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__ */ jsx(Fragment, { children: /* @__PURE__ */ 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__ */ jsx(
                      Input,
                      __spreadValues({
                        "data-testid": `${field.name}_field`,
                        placeholder: field.placeholder,
                        pattern: field.pattern,
                        type: field.inputMode
                      }, register(field.name))
                    ),
                    toggle: /* @__PURE__ */ jsx(
                      Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const toggleField = field;
                          return /* @__PURE__ */ jsx(Box, { "data-testid": `${toggleField.name}_field`, children: /* @__PURE__ */ jsx(
                            Switch,
                            __spreadProps(__spreadValues({}, renderField), {
                              defaultChecked: toggleField.defaultValue === "true"
                            })
                          ) });
                        }
                      }
                    ),
                    hidden: /* @__PURE__ */ jsx(
                      Input,
                      __spreadValues({
                        "data-testid": `${field.name}_field`,
                        hidden: true,
                        type: "none"
                      }, register(field.name))
                    ),
                    number: /* @__PURE__ */ jsx(
                      Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                          const numberField = field;
                          return /* @__PURE__ */ jsx(
                            NumberInput,
                            __spreadProps(__spreadValues({}, rest), {
                              name: numberField.name,
                              min: numberField.min,
                              max: numberField.max,
                              step: numberField.step,
                              placeholder: numberField.placeholder
                            })
                          );
                        }
                      }
                    ),
                    radio: /* @__PURE__ */ jsx(
                      Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                          const radioField = field;
                          return /* @__PURE__ */ jsx(Box, { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsx(
                            RadioGroup,
                            __spreadProps(__spreadValues({}, rest), {
                              isAttached: radioField.isAttached,
                              options: radioField.options || [],
                              defaultValue: radioField.defaultValue,
                              onChange: (nextValue) => {
                                setValue(radioField.name, nextValue);
                                setFormMethods(formMethods);
                              }
                            })
                          ) });
                        }
                      }
                    ),
                    select: /* @__PURE__ */ jsx(
                      Controller,
                      {
                        name: field.name,
                        control,
                        render: ({ field: renderField }) => {
                          const _a3 = renderField, rest = __objRest(_a3, ["ref"]);
                          const selectField = field;
                          return /* @__PURE__ */ jsx(Box, { "data-testid": `${selectField.name}_field`, children: /* @__PURE__ */ jsx(
                            Select,
                            __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__ */ jsx(
                      Textarea,
                      __spreadProps(__spreadValues({}, register(field.name)), {
                        "data-testid": `${field.name}_field`,
                        placeholder: field.placeholder
                      })
                    )
                  }[field.fieldType || "text"]
                },
                field.name
              ) });
            }
          ),
          /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsxs(ButtonGroup, { children: [
            /* @__PURE__ */ jsx(
              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__ */ jsx(DevTool, { control }) : null
  ] });
}

export { Form as default };
//# sourceMappingURL=Form.js.map
