import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect, Fragment as Fragment$1 } from 'react';
import { chakra, VStack, Box, ButtonGroup, Heading, Text, Input, Switch, RadioGroup, Stack, Radio, Textarea, Checkbox } 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$1 from '../Inputs/RadioGroup/RadioGroup.js';
import Select from '../Inputs/Select/Select.js';
import RPSlider from '../Inputs/Slider/RPSlider.js';
import ColumnSelect from '../Inputs/ColumnSelect/ColumnSelect.js';
import Button from '../Button/Button.js';
import PasswordInput from '../Inputs/PasswordInput/PasswordInput.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 generateValidationSchemaObject(fields) {
  let schema = fields.filter((field) => field.fieldType !== "displaySection").map((field) => {
    if (field.fieldType === "custom" && "fields" in field) {
      return generateValidationSchemaObject(field.fields);
    } else {
      return { name: field.name, schema: field.schema };
    }
  });
  return schema.flat();
}
function generateInitialValuesObject(fields) {
  const initialValues = fields.filter((field) => field.fieldType !== "displaySection").map((field) => {
    if (field.fieldType === "custom" && "fields" in field) {
      return generateInitialValuesObject(field.fields);
    } else {
      if (field.fieldType === "select" && field.defaultValue) {
        const selectField = field;
        return {
          name: selectField.name,
          defaultValue: selectField.isMulti ? selectField.defaultValue : selectField.defaultValue.value
        };
      } else {
        return { name: field.name, defaultValue: field.defaultValue };
      }
    }
  });
  return initialValues.flat();
}
function Form({
  onValid,
  onInvalid,
  fields,
  button,
  autofocus,
  mode,
  developerView,
  isDisabled,
  isFetching,
  actions,
  onInvalidFormValidation
}) {
  var _a;
  const filteredFields = fields.filter((field) => !field.hide);
  const initialSchemaValues = Object.fromEntries(
    generateInitialValuesObject(filteredFields).map((fieldObj) => [
      fieldObj.name,
      fieldObj.defaultValue
    ])
  );
  const schema = Object.fromEntries(
    generateValidationSchemaObject(filteredFields).map((fieldObj) => [
      fieldObj.name,
      fieldObj.schema
    ])
  );
  const validationSchema = Yup.object().shape(schema);
  const [validationContext, setValidationContext] = useState({});
  const inputRef = useRef();
  useEffect(() => {
    var _a2;
    if (autofocus && inputRef)
      (_a2 = inputRef.current) == null ? void 0 : _a2.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),
    context: validationContext
  });
  useEffect(() => {
    setFormMethods(formMethods);
  }, []);
  const {
    register,
    handleSubmit,
    setValue,
    control,
    formState: { isSubmitting, errors }
  } = formMethods;
  const isFormDisabled = isSubmitting || isDisabled || isFetching;
  const isFormSubmissionDisabled = isFormDisabled || Object.keys(errors).length > 0;
  useEffect(() => {
    if (isFormSubmissionDisabled && onInvalidFormValidation !== void 0) {
      onInvalidFormValidation();
    }
  }, [isFormSubmissionDisabled]);
  const allActions = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Button,
      {
        variant: (_a = button.variant) != null ? _a : "brand",
        "aria-label": button.label,
        "data-testid": button.label,
        type: "submit",
        isLoading: isSubmitting || isFetching,
        isDisabled: isFormSubmissionDisabled,
        children: button.text
      }
    ),
    actions
  ] });
  const mapFields = (fields2) => {
    const mappedFields = fields2.map(
      (_a2) => {
        var _b = _a2, {
          label,
          columns,
          help,
          description,
          footerDescription,
          tooltip,
          heading,
          showRequiredIndicator
        } = _b, field = __objRest(_b, [
          "label",
          "columns",
          "help",
          "description",
          "footerDescription",
          "tooltip",
          "heading",
          "showRequiredIndicator"
        ]);
        var _a3;
        if (field.fieldType === "displaySection") {
          return /* @__PURE__ */ jsxs(Box, { children: [
            heading && /* @__PURE__ */ jsx(Heading, { as: "h5", size: "md", children: heading }),
            description && /* @__PURE__ */ jsx(Text, { children: description })
          ] }, field.name);
        }
        if (field.fieldType === "repeater") {
          return /* @__PURE__ */ jsx(Fragment, {});
        }
        if (field.fieldType === "custom") {
          let f = field;
          return /* @__PURE__ */ jsx(
            f.component,
            {
              form: formMethods,
              setValidationContext
            },
            field.name
          );
        }
        return /* @__PURE__ */ jsx(Fragment$1, { children: /* @__PURE__ */ jsx(
          FormField,
          {
            description,
            footerDescription,
            tooltip,
            isRequired: field.fieldType === "hidden" ? false : field.isRequired !== false,
            isDisabled: field.isDisabled || isFormDisabled,
            hidden: field.fieldType === "hidden",
            style: columns && { gridColumn: `span ${columns}` },
            label,
            isInvalid: !!errors[field.name],
            errorText: (_a3 = errors[field.name]) == null ? void 0 : _a3.message,
            helpText: help,
            showRequiredIndicator,
            children: {
              text: /* @__PURE__ */ jsx(
                Input,
                __spreadValues({
                  "data-testid": `${field.name}_field`,
                  placeholder: field.placeholder,
                  pattern: field.pattern,
                  type: field.inputMode
                }, register(field.name))
              ),
              password: /* @__PURE__ */ jsx(
                Controller,
                {
                  name: field.name,
                  control,
                  render: ({ field: renderField }) => {
                    const _a4 = renderField, rest = __objRest(_a4, ["ref"]);
                    const passwordField = field;
                    return /* @__PURE__ */ jsx(
                      PasswordInput,
                      __spreadProps(__spreadValues({}, rest), {
                        name: passwordField.name,
                        placeholder: passwordField.placeholder,
                        pattern: passwordField.pattern,
                        type: passwordField.inputMode,
                        defaultShowPassword: passwordField.defaultShowPassword,
                        showEyeIndicator: passwordField.showEyeIndicator
                      })
                    );
                  }
                }
              ),
              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 _a4 = renderField, rest = __objRest(_a4, ["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 _a4 = renderField, rest = __objRest(_a4, ["ref"]);
                    const radioField = field;
                    if (radioField.radioVariant === "circle") {
                      return /* @__PURE__ */ jsx(Box, { "data-testid": `${field.name}_field`, mt: 2, children: /* @__PURE__ */ jsx(
                        RadioGroup,
                        __spreadProps(__spreadValues({}, rest), {
                          defaultValue: field.defaultValue,
                          onChange: (nextValue) => {
                            setValue(radioField.name, nextValue);
                            setFormMethods(formMethods);
                          },
                          children: /* @__PURE__ */ jsx(Stack, { direction: radioField.radioStackDirection, children: radioField.options.map(
                            (_b2) => {
                              var _c = _b2, { label: label2, value, disabled, invalid } = _c, otherOptionProps = __objRest(_c, ["label", "value", "disabled", "invalid"]);
                              return /* @__PURE__ */ jsx(
                                Radio,
                                __spreadProps(__spreadValues({
                                  value: `${value}`,
                                  isDisabled: disabled,
                                  isInvalid: invalid
                                }, otherOptionProps), {
                                  children: /* @__PURE__ */ jsx(
                                    Text,
                                    {
                                      "aria-invalid": invalid,
                                      _invalid: {
                                        textColor: "red.500",
                                        borderColor: "red.500"
                                      },
                                      children: label2
                                    }
                                  )
                                }),
                                `${value}`
                              );
                            }
                          ) })
                        })
                      ) });
                    }
                    return /* @__PURE__ */ jsx(Box, { "data-testid": `${field.name}_field`, children: /* @__PURE__ */ jsx(
                      RadioGroup$1,
                      __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 _a4 = renderField, rest = __objRest(_a4, ["ref"]);
                    const selectField = field;
                    return /* @__PURE__ */ jsx(Box, { "data-testid": `${selectField.name}_field`, children: /* @__PURE__ */ jsx(
                      Select,
                      __spreadProps(__spreadValues({
                        menuPlacement: "auto"
                      }, rest), {
                        innerRef: selectField.innerRef,
                        placeholder: selectField.placeholder,
                        isLoading: selectField.isLoading,
                        isMulti: selectField.isMulti,
                        options: selectField.options,
                        defaultValue: selectField.defaultValue,
                        onChange: (nextValue) => {
                          setValue(selectField.name, nextValue);
                          setFormMethods(formMethods);
                        }
                      })
                    ) });
                  }
                }
              ),
              columnSelect: /* @__PURE__ */ jsx(
                Controller,
                {
                  name: field.name,
                  control,
                  render: ({ field: renderField }) => {
                    const _a4 = renderField, rest = __objRest(_a4, ["ref"]);
                    const columnSelectField = field;
                    return /* @__PURE__ */ jsx(Box, { "data-testid": `${columnSelectField.name}_field`, children: /* @__PURE__ */ jsx(
                      ColumnSelect,
                      __spreadProps(__spreadValues({
                        menuPlacement: "auto"
                      }, rest), {
                        innerRef: columnSelectField.innerRef,
                        placeholder: columnSelectField.placeholder,
                        isLoading: columnSelectField.isLoading,
                        options: columnSelectField.options,
                        defaultValue: columnSelectField.defaultValue,
                        firstTextPosition: columnSelectField.firstTextPosition,
                        headerColumns: columnSelectField.headerColumns,
                        footer: columnSelectField.footer,
                        singleValueText: columnSelectField.singleValueText,
                        onChange: (nextValue) => {
                          setValue(columnSelectField.name, nextValue);
                          setFormMethods(formMethods);
                        }
                      })
                    ) });
                  }
                }
              ),
              textarea: /* @__PURE__ */ jsx(
                Textarea,
                __spreadProps(__spreadValues({}, register(field.name)), {
                  "data-testid": `${field.name}_field`,
                  placeholder: field.placeholder
                })
              ),
              slider: /* @__PURE__ */ jsx(
                Controller,
                {
                  name: field.name,
                  control,
                  render: ({ field: renderField }) => {
                    const _a4 = renderField, rest = __objRest(_a4, ["ref"]);
                    const sliderField = field;
                    const _b2 = sliderField, sliderRest = __objRest(_b2, ["fieldType"]);
                    return /* @__PURE__ */ jsx(Box, { "data-testid": `${sliderField.name}_field`, children: /* @__PURE__ */ jsx(
                      RPSlider,
                      __spreadProps(__spreadValues(__spreadValues({}, sliderRest), rest), {
                        onChange: (nextValue) => {
                          setValue(sliderField.name, nextValue);
                          setFormMethods(formMethods);
                        }
                      })
                    ) });
                  }
                }
              ),
              displaySection: /* @__PURE__ */ jsx(Fragment, {}),
              checkbox: /* @__PURE__ */ jsx(
                Controller,
                {
                  name: field.name,
                  control,
                  render: ({ field: renderField }) => {
                    const checkboxField = field;
                    return /* @__PURE__ */ jsx(Box, { "data-testid": `${checkboxField.name}_field`, children: /* @__PURE__ */ jsx(Checkbox, __spreadProps(__spreadValues({}, renderField), { children: checkboxField.text })) });
                  }
                }
              )
            }[field.fieldType || "text"]
          },
          field.name
        ) }, field.name);
      }
    );
    return mappedFields.flat();
  };
  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: [
          mapFields(fields),
          button.spanFullWidth ? allActions : /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(ButtonGroup, { children: allActions }) })
        ] }) })
      }
    ),
    developerView ? /* @__PURE__ */ jsx(DevTool, { control }) : null
  ] });
}

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