import React__default, { forwardRef, useContext, useState, useRef, useEffect, useMemo, cloneElement } from "react";
import cs from "../_util/classNames.js";
import { isObject, isUndefined, isFunction, isArray } from "../_util/is.js";
import Grid from "../Grid/index.js";
import { VALIDATE_STATUS } from "./interface.js";
import FormControl from "./control.js";
import { FormItemContext, FormListContext, FormContext } from "./context.js";
import { ConfigContext } from "../ConfigProvider/index.js";
import omit from "../_util/omit.js";
import FormItemLabel from "./form-label.js";
import { formatValidateMsg } from "./utils.js";
import { jsx, jsxs, Fragment } from "../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js";
import CSSTransition from "../../../../../../react-transition-group@4.4.5_biqbaboplfbrettd7655fr4n2y/node_modules/react-transition-group/esm/CSSTransition.js";
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var __spreadArray = globalThis && globalThis.__spreadArray || function(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i);
        ar[i] = from[i];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
};
var Row = Grid.Row;
var Col = Grid.Col;
var FormItemTip = function(_a) {
  var _b;
  var prefixCls = _a.prefixCls, help = _a.help, propsErrors = _a.errors, warnings = _a.warnings;
  var errorTip = propsErrors.map(function(item, i) {
    if (item) {
      return /* @__PURE__ */ jsx("div", {
        role: "alert",
        children: item.message
      }, i);
    }
  });
  var warningTip = [];
  warnings.map(function(item, i) {
    warningTip.push(/* @__PURE__ */ jsx("div", {
      role: "alert",
      className: prefixCls + "-message-help-warning",
      children: item
    }, i));
  });
  var isHelpTip = !isUndefined(help) || !!warningTip.length;
  var visible = isHelpTip || !!errorTip.length;
  return visible && /* @__PURE__ */ jsx(CSSTransition, {
    in: visible,
    appear: true,
    classNames: "formblink",
    timeout: 300,
    unmountOnExit: true,
    children: /* @__PURE__ */ jsx("div", {
      className: cs(prefixCls + "-message", (_b = {}, _b[prefixCls + "-message-help"] = isHelpTip, _b)),
      children: !isUndefined(help) ? help : /* @__PURE__ */ jsxs(Fragment, {
        children: [errorTip.length > 0 && errorTip, warningTip.length > 0 && warningTip]
      })
    })
  });
};
var Item = function(props, ref) {
  var _a, _b, _c, _d;
  var _e, _f;
  var _g = useContext(ConfigContext), getPrefixCls = _g.getPrefixCls, prefix = _g.prefixCls;
  var topFormContext = useContext(FormItemContext);
  var formListContext = useContext(FormListContext);
  var _h = __read(useState(null), 2), errors = _h[0], setErrors = _h[1];
  var _j = __read(useState(null), 2), warnings = _j[0], setWarnings = _j[1];
  var formContext = useContext(FormContext);
  var prefixCls = formContext.prefixCls || getPrefixCls("form");
  var formLayout = props.layout || formContext.layout;
  var labelAlign = props.labelAlign || formContext.labelAlign;
  var isDestroyed = useRef(false);
  var updateInnerFormItem = function(field, params) {
    if (params === void 0) {
      params = {};
    }
    if (isDestroyed.current) {
      return;
    }
    var _a2 = params || {}, errors2 = _a2.errors, warnings2 = _a2.warnings;
    setErrors(function(innerErrors) {
      var newErrors = __assign({}, innerErrors || {});
      if (errors2) {
        newErrors[field] = errors2;
      } else {
        delete newErrors[field];
      }
      return newErrors;
    });
    setWarnings(function(current) {
      var newVal = __assign({}, current || {});
      if (warnings2 && warnings2.length) {
        newVal[field] = warnings2;
      } else {
        delete newVal[field];
      }
      return newVal;
    });
  };
  var updateFormItem = isObject(props.noStyle) && props.noStyle.showErrorTip && topFormContext.updateFormItem ? topFormContext.updateFormItem : updateInnerFormItem;
  useEffect(function() {
    isDestroyed.current = false;
    return function() {
      isDestroyed.current = true;
      setErrors(null);
      setWarnings(null);
    };
  }, []);
  var contextProps = __assign(__assign({}, formContext), {
    validateMessages: formContext.validateMessages && formatValidateMsg(formContext.validateMessages, {
      label: props.label
    }),
    prefixCls,
    updateFormItem,
    disabled: "disabled" in props ? props.disabled : formContext.disabled
  });
  var label = props.label, extra = props.extra, className = props.className, style = props.style, validateStatus = props.validateStatus, hidden = props.hidden, rest = __rest(props, ["label", "extra", "className", "style", "validateStatus", "hidden"]);
  var labelClassNames = cs(prefixCls + "-label-item", (_a = {}, _a[prefixCls + "-label-item-left"] = labelAlign === "left", _a));
  var errorInfo = errors ? Object.values(errors) : [];
  var warningInfo = warnings ? Object.values(warnings).reduce(function(total, next) {
    return total.concat(next);
  }, []) : [];
  var itemStatus = useMemo(function() {
    if (validateStatus) {
      return validateStatus;
    }
    if (errorInfo.length) {
      return VALIDATE_STATUS.error;
    }
    if (warningInfo.length) {
      return VALIDATE_STATUS.warning;
    }
    return void 0;
  }, [errors, warnings, validateStatus]);
  var hasHelp = useMemo(function() {
    return !isUndefined(props.help) || warningInfo.length > 0;
  }, [props.help, warnings]);
  var classNames = cs(prefixCls + "-item", (_b = {}, _b[prefixCls + "-item-error"] = hasHelp || !validateStatus && itemStatus === VALIDATE_STATUS.error, _b[prefixCls + "-item-status-" + itemStatus] = itemStatus, _b[prefixCls + "-item-has-help"] = hasHelp, _b[prefixCls + "-item-hidden"] = hidden, _b[prefixCls + "-item-has-feedback"] = itemStatus && props.hasFeedback, _b), prefixCls + "-layout-" + formLayout, className);
  var cloneElementWithDisabled = function() {
    var _a2, _b2;
    var field = props.field, children = props.children;
    var disabled = "disabled" in props ? props.disabled : formContext.disabled;
    if (isFunction(children)) {
      return /* @__PURE__ */ jsx(FormControl, {
        ...__assign({
          disabled
        }, props, field ? {
          key: field,
          _key: field
        } : {}),
        children: function() {
          var rest2 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            rest2[_i] = arguments[_i];
          }
          return children.apply(void 0, __spreadArray([], __read(rest2), false));
        }
      });
    }
    if (isArray(children)) {
      var childrenDom = React__default.Children.map(children, function(child, i) {
        var key2 = isObject(child) && child.key || i;
        var childProps2 = !isUndefined(disabled) ? {
          key: key2,
          disabled
        } : {
          key: key2
        };
        return isObject(child) ? cloneElement(child, childProps2) : child;
      });
      return /* @__PURE__ */ jsx(FormControl, {
        ...__assign({}, props, {
          field: void 0
        }),
        children: childrenDom
      });
    }
    if (React__default.Children.count(children) === 1) {
      if (field) {
        var key = ((_a2 = formListContext === null || formListContext === void 0 ? void 0 : formListContext.getItemKey) === null || _a2 === void 0 ? void 0 : _a2.call(formListContext, field)) || field;
        return /* @__PURE__ */ jsx(FormControl, {
          ...__assign({
            disabled
          }, props, {
            key,
            _key: key
          }),
          children
        });
      }
      if (isObject(children)) {
        if ((_b2 = children.type) === null || _b2 === void 0 ? void 0 : _b2.isFormControl) {
          return children;
        }
        var childProps = isUndefined(disabled) ? {} : {
          disabled
        };
        return /* @__PURE__ */ jsx(FormControl, {
          ...__assign({}, props, {
            field: void 0
          }),
          children: cloneElement(children, childProps)
        });
      }
    }
    return children;
  };
  var FormItemContext$1 = FormItemContext;
  var newFormContext = __assign({}, formContext);
  if (!props.noStyle) {
    newFormContext.wrapperCol = void 0;
    newFormContext.labelCol = void 0;
  }
  return /* @__PURE__ */ jsx(FormContext.Provider, {
    value: newFormContext,
    children: /* @__PURE__ */ jsx(FormItemContext$1.Provider, {
      value: contextProps,
      children: props.noStyle ? cloneElementWithDisabled() : /* @__PURE__ */ jsxs(Row, {
        ...__assign({
          ref
        }, omit(rest, ["children", "prefixCls", "store", "initialValue", "field", "labelCol", "wrapperCol", "colon", "disabled", "rules", "trigger", "triggerPropName", "validateTrigger", "noStyle", "required", "hasFeedback", "help", "normalize", "formatter", "getValueFromEvent", "shouldUpdate", "field", "isInner", "labelAlign", "layout", "requiredSymbol", "isFormList"]), {
          className: classNames,
          div: formLayout !== "horizontal",
          style
        }),
        children: [label ? /* @__PURE__ */ jsx(Col, {
          ...__assign({}, props.labelCol || formContext.labelCol, {
            className: cs(labelClassNames, (_e = props.labelCol) === null || _e === void 0 ? void 0 : _e.className, (_f = formContext.labelCol) === null || _f === void 0 ? void 0 : _f.className, (_c = {}, _c[prefixCls + "-label-item-flex"] = !props.labelCol && !formContext.labelCol, _c))
          }),
          children: /* @__PURE__ */ jsx(FormItemLabel, {
            htmlFor: props.field && formContext.getFormElementId(props.field),
            label,
            prefix,
            requiredSymbol: "requiredSymbol" in props ? props.requiredSymbol : formContext.requiredSymbol,
            required: props.required,
            rules: props.rules,
            showColon: "colon" in props ? props.colon : formContext.colon
          })
        }) : null, /* @__PURE__ */ jsxs(Col, {
          ...__assign({
            className: cs(prefixCls + "-item-wrapper", (_d = {}, _d[prefixCls + "-item-wrapper-flex"] = !props.wrapperCol && !formContext.wrapperCol, _d))
          }, props.wrapperCol || formContext.wrapperCol),
          children: [cloneElementWithDisabled(), /* @__PURE__ */ jsx(FormItemTip, {
            prefixCls,
            help: props.help,
            errors: errorInfo,
            warnings: warningInfo
          }), extra && /* @__PURE__ */ jsx("div", {
            className: prefixCls + "-extra",
            children: extra
          })]
        })]
      })
    })
  });
};
var ItemComponent = forwardRef(Item);
ItemComponent.defaultProps = {
  trigger: "onChange",
  triggerPropName: "value"
};
ItemComponent.displayName = "FormItem";
const FormItem = ItemComponent;
export {
  FormItem as default
};
//# sourceMappingURL=form-item.js.map
