import _typeof from "@babel/runtime/helpers/esm/typeof";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { __rest } from "tslib";
import * as React from 'react';
import { useContext } from 'react';
import classNames from 'classnames';
import { Field } from 'rc-field-form';
import FieldContext from "rc-field-form/es/FieldContext";
import { supportRef } from "rc-util/es/ref";
import omit from "rc-util/es/omit";
import Row from '../grid/row';
import { ConfigContext } from '../config-provider';
import { tuple } from '../_util/type';
import devWarning from '../_util/devWarning';
import FormItemLabel from './FormItemLabel';
import FormItemInput from './FormItemInput';
import { FormContext, NoStyleItemContext } from './context';
import { toArray, getFieldId } from './util';
import { cloneElement, isValidElement } from '../_util/reactNode';
import useFrameState from './hooks/useFrameState';
import useDebounce from './hooks/useDebounce';
import useItemRef from './hooks/useItemRef';
var NAME_SPLIT = '__SPLIT__';
var ValidateStatuses = tuple('success', 'warning', 'error', 'validating', '');
var MemoInput = /*#__PURE__*/React.memo(function (_ref) {
  var children = _ref.children;
  return children;
}, function (prev, next) {
  return prev.value === next.value && prev.update === next.update;
});

function hasValidName(name) {
  if (name === null) {
    devWarning(false, 'Form.Item', '`null` is passed as `name` property');
  }

  return !(name === undefined || name === null);
}

function genEmptyMeta() {
  return {
    errors: [],
    warnings: [],
    touched: false,
    validating: false,
    name: []
  };
}

function FormItem(props) {
  var name = props.name,
      fieldKey = props.fieldKey,
      noStyle = props.noStyle,
      dependencies = props.dependencies,
      customizePrefixCls = props.prefixCls,
      style = props.style,
      className = props.className,
      shouldUpdate = props.shouldUpdate,
      hasFeedback = props.hasFeedback,
      help = props.help,
      rules = props.rules,
      validateStatus = props.validateStatus,
      children = props.children,
      required = props.required,
      label = props.label,
      messageVariables = props.messageVariables,
      _props$trigger = props.trigger,
      trigger = _props$trigger === void 0 ? 'onChange' : _props$trigger,
      validateTrigger = props.validateTrigger,
      hidden = props.hidden,
      restProps = __rest(props, ["name", "fieldKey", "noStyle", "dependencies", "prefixCls", "style", "className", "shouldUpdate", "hasFeedback", "help", "rules", "validateStatus", "children", "required", "label", "messageVariables", "trigger", "validateTrigger", "hidden"]);

  var _useContext = useContext(ConfigContext),
      getPrefixCls = _useContext.getPrefixCls;

  var _useContext2 = useContext(FormContext),
      formName = _useContext2.name,
      requiredMark = _useContext2.requiredMark;

  var isRenderProps = typeof children === 'function';
  var notifyParentMetaChange = useContext(NoStyleItemContext);

  var _useContext3 = useContext(FieldContext),
      contextValidateTrigger = _useContext3.validateTrigger;

  var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : contextValidateTrigger;
  var hasName = hasValidName(name);
  var prefixCls = getPrefixCls('form', customizePrefixCls); // ======================== Errors ========================
  // >>>>> Collect sub field errors

  var _useFrameState = useFrameState({}),
      _useFrameState2 = _slicedToArray(_useFrameState, 2),
      subFieldErrors = _useFrameState2[0],
      setSubFieldErrors = _useFrameState2[1]; // >>>>> Current field errors


  var _React$useState = React.useState(function () {
    return genEmptyMeta();
  }),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      meta = _React$useState2[0],
      setMeta = _React$useState2[1];

  var onMetaChange = function onMetaChange(nextMeta) {
    // Destroy will reset all the meta
    setMeta(nextMeta.destroy ? genEmptyMeta() : nextMeta); // Bump to parent since noStyle

    if (noStyle && notifyParentMetaChange) {
      var namePath = nextMeta.name;

      if (fieldKey !== undefined) {
        namePath = Array.isArray(fieldKey) ? fieldKey : [fieldKey];
      }

      notifyParentMetaChange(nextMeta, namePath);
    }
  }; // >>>>> Collect noStyle Field error to the top FormItem


  var onSubItemMetaChange = function onSubItemMetaChange(subMeta, uniqueKeys) {
    // Only `noStyle` sub item will trigger
    setSubFieldErrors(function (prevSubFieldErrors) {
      var clone = _extends({}, prevSubFieldErrors); // name: ['user', 1] + key: [4] = ['user', 4]


      var mergedNamePath = [].concat(_toConsumableArray(subMeta.name.slice(0, -1)), _toConsumableArray(uniqueKeys));
      var mergedNameKey = mergedNamePath.join(NAME_SPLIT);

      if (subMeta.destroy) {
        // Remove
        delete clone[mergedNameKey];
      } else {
        // Update
        clone[mergedNameKey] = subMeta;
      }

      return clone;
    });
  }; // >>>>> Get merged errors


  var _React$useMemo = React.useMemo(function () {
    var errorList = _toConsumableArray(meta.errors);

    var warningList = _toConsumableArray(meta.warnings);

    Object.values(subFieldErrors).forEach(function (subFieldError) {
      errorList.push.apply(errorList, _toConsumableArray(subFieldError.errors || []));
      warningList.push.apply(warningList, _toConsumableArray(subFieldError.warnings || []));
    });
    return [errorList, warningList];
  }, [subFieldErrors, meta.errors, meta.warnings]),
      _React$useMemo2 = _slicedToArray(_React$useMemo, 2),
      mergedErrors = _React$useMemo2[0],
      mergedWarnings = _React$useMemo2[1];

  var debounceErrors = useDebounce(mergedErrors);
  var debounceWarnings = useDebounce(mergedWarnings); // ===================== Children Ref =====================

  var getItemRef = useItemRef(); // ======================== Render ========================

  function renderLayout(baseChildren, fieldId, isRequired) {
    var _itemClassName;

    if (noStyle && !hidden) {
      return baseChildren;
    } // ======================== Status ========================


    var mergedValidateStatus = '';

    if (validateStatus !== undefined) {
      mergedValidateStatus = validateStatus;
    } else if (meta === null || meta === void 0 ? void 0 : meta.validating) {
      mergedValidateStatus = 'validating';
    } else if (debounceErrors.length) {
      mergedValidateStatus = 'error';
    } else if (debounceWarnings.length) {
      mergedValidateStatus = 'warning';
    } else if (meta === null || meta === void 0 ? void 0 : meta.touched) {
      mergedValidateStatus = 'success';
    }

    var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, "".concat(prefixCls, "-item"), true), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-with-help"), help || debounceErrors.length || debounceWarnings.length), _defineProperty(_itemClassName, "".concat(className), !!className), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-feedback"), mergedValidateStatus && hasFeedback), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-success"), mergedValidateStatus === 'success'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-warning"), mergedValidateStatus === 'warning'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-has-error"), mergedValidateStatus === 'error'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-is-validating"), mergedValidateStatus === 'validating'), _defineProperty(_itemClassName, "".concat(prefixCls, "-item-hidden"), hidden), _itemClassName); // ======================= Children =======================

    return /*#__PURE__*/React.createElement(Row, _extends({
      className: classNames(itemClassName),
      style: style,
      key: "row"
    }, omit(restProps, ['colon', 'extra', 'getValueFromEvent', 'getValueProps', 'htmlFor', 'id', 'initialValue', 'isListField', 'labelAlign', 'labelCol', 'normalize', 'preserve', 'tooltip', 'validateFirst', 'valuePropName', 'wrapperCol', '_internalItemRender'])), /*#__PURE__*/React.createElement(FormItemLabel, _extends({
      htmlFor: fieldId,
      required: isRequired,
      requiredMark: requiredMark
    }, props, {
      prefixCls: prefixCls
    })), /*#__PURE__*/React.createElement(FormItemInput, _extends({}, props, meta, {
      errors: debounceErrors,
      warnings: debounceWarnings,
      prefixCls: prefixCls,
      status: mergedValidateStatus,
      validateStatus: mergedValidateStatus,
      help: help
    }), /*#__PURE__*/React.createElement(NoStyleItemContext.Provider, {
      value: onSubItemMetaChange
    }, baseChildren)));
  }

  if (!hasName && !isRenderProps && !dependencies) {
    return renderLayout(children);
  }

  var variables = {};

  if (typeof label === 'string') {
    variables.label = label;
  } else if (name) {
    variables.label = String(name);
  }

  if (messageVariables) {
    variables = _extends(_extends({}, variables), messageVariables);
  } // >>>>> With Field


  return /*#__PURE__*/React.createElement(Field, _extends({}, props, {
    messageVariables: variables,
    trigger: trigger,
    validateTrigger: mergedValidateTrigger,
    // @ts-ignore
    onMetaChange: onMetaChange
  }), function (control, renderMeta, context) {
    var mergedName = toArray(name).length && renderMeta ? renderMeta.name : [];
    var fieldId = getFieldId(mergedName, formName);
    var isRequired = required !== undefined ? required : !!(rules && rules.some(function (rule) {
      // @ts-ignore
      if (rule && _typeof(rule) === 'object' && rule.required && !rule.warningOnly) {
        return true;
      }

      if (typeof rule === 'function') {
        var ruleEntity = rule(context); // @ts-ignore

        return ruleEntity && ruleEntity.required && !ruleEntity.warningOnly;
      }

      return false;
    })); // ======================= Children =======================

    var mergedControl = _extends({}, control);

    var childNode = null;
    devWarning(!(shouldUpdate && dependencies), 'Form.Item', "`shouldUpdate` and `dependencies` shouldn't be used together. See https://ant.design/components/form/#dependencies.");

    if (Array.isArray(children) && hasName) {
      devWarning(false, 'Form.Item', '`children` is array of render props cannot have `name`.');
      childNode = children;
    } else if (isRenderProps && (!(shouldUpdate || dependencies) || hasName)) {
      devWarning(!!(shouldUpdate || dependencies), 'Form.Item', '`children` of render props only work with `shouldUpdate` or `dependencies`.');
      devWarning(!hasName, 'Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
    } else if (dependencies && !isRenderProps && !hasName) {
      devWarning(false, 'Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
    } else if (isValidElement(children)) {
      devWarning(children.props.defaultValue === undefined, 'Form.Item', '`defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.');

      var childProps = _extends(_extends({}, children.props), mergedControl);

      if (!childProps.id) {
        childProps.id = fieldId;
      }

      if (supportRef(children)) {
        childProps.ref = getItemRef(mergedName, children);
      } // We should keep user origin event handler


      var triggers = new Set([].concat(_toConsumableArray(toArray(trigger)), _toConsumableArray(toArray(mergedValidateTrigger))));
      triggers.forEach(function (eventName) {
        childProps[eventName] = function () {
          var _a2, _c2;

          var _a, _b, _c;

          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }

          (_a = mergedControl[eventName]) === null || _a === void 0 ? void 0 : (_a2 = _a).call.apply(_a2, [mergedControl].concat(args));
          (_c = (_b = children.props)[eventName]) === null || _c === void 0 ? void 0 : (_c2 = _c).call.apply(_c2, [_b].concat(args));
        };
      });
      childNode = /*#__PURE__*/React.createElement(MemoInput, {
        value: mergedControl[props.valuePropName || 'value'],
        update: children
      }, cloneElement(children, childProps));
    } else if (isRenderProps && (shouldUpdate || dependencies) && !hasName) {
      childNode = children(context);
    } else {
      devWarning(!mergedName.length, 'Form.Item', '`name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.');
      childNode = children;
    }

    return renderLayout(childNode, fieldId, isRequired);
  });
}

export default FormItem;