'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var cls = require('classnames');
var constants = require('../../utils/constants.js');
var CodeInput_tokens = require('./CodeInput.tokens.js');
var CodeInput_styles = require('./CodeInput.styles.js');
var base = require('./variations/_view/base.js');
var base$1 = require('./variations/_size/base.js');
var base$2 = require('./variations/_disabled/base.js');
var initialValuesHelper = require('../../utils/initialValuesHelper.js');
var useCodeHook = require('../../hooks/useCodeHook.js');
var useDidMountEffect = require('../../hooks/useDidMountEffect.js');
var handleCodeError = require('./utils/handleCodeError.js');
var getSizeValueFromProp = require('../../utils/getSizeValueFromProp.js');
var handleItemError = require('./utils/handleItemError.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);
var cls__default = /*#__PURE__*/_interopDefault(cls);

var _Separator;
var _excluded = ["className", "placeholder", "autoFocus", "codeLength", "caption", "captionAlign", "width", "view", "size", "hidden", "disabled", "isError", "allowedSymbols", "itemErrorBehavior", "codeErrorBehavior", "autoComplete", "inputMode", "setIsError", "onChange", "onFullCodeEnter"];
var codeInputRoot = function codeInputRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (_ref, ref) {
    var className = _ref.className,
      placeholder = _ref.placeholder,
      autoFocus = _ref.autoFocus,
      _ref$codeLength = _ref.codeLength,
      codeLength = _ref$codeLength === void 0 ? 6 : _ref$codeLength,
      caption = _ref.caption,
      _ref$captionAlign = _ref.captionAlign,
      captionAlign = _ref$captionAlign === void 0 ? 'left' : _ref$captionAlign,
      width = _ref.width,
      view = _ref.view,
      size = _ref.size,
      hidden = _ref.hidden,
      disabled = _ref.disabled,
      isError = _ref.isError,
      _ref$allowedSymbols = _ref.allowedSymbols,
      allowedSymbols = _ref$allowedSymbols === void 0 ? constants.ONLY_DIGITS_PATTERN : _ref$allowedSymbols,
      _ref$itemErrorBehavio = _ref.itemErrorBehavior,
      itemErrorBehavior = _ref$itemErrorBehavio === void 0 ? 'remove-symbol' : _ref$itemErrorBehavio,
      _ref$codeErrorBehavio = _ref.codeErrorBehavior,
      codeErrorBehavior = _ref$codeErrorBehavio === void 0 ? 'remove-code' : _ref$codeErrorBehavio,
      _ref$autoComplete = _ref.autoComplete,
      autoComplete = _ref$autoComplete === void 0 ? 'one-time-code' : _ref$autoComplete,
      inputMode = _ref.inputMode,
      setIsError = _ref.setIsError,
      onChange = _ref.onChange,
      onFullCodeEnter = _ref.onFullCodeEnter,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(_ref, _excluded);
    var _useState = React.useState(initialValuesHelper.getCodeValue(codeLength, '')),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      code = _useState2[0],
      setCode = _useState2[1];
    var _useState3 = React.useState(code.join('')),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      originalValue = _useState4[0],
      setOriginalValue = _useState4[1];
    var inputRefs = React.useRef([]);
    var inputContainerRef = React.useRef(null);
    var captionRef = React.useRef(null);
    var fieldPattern = initialValuesHelper.getFieldPattern(allowedSymbols);
    var placeholderValue = initialValuesHelper.getPlaceholderValue(codeLength, placeholder);
    var parts = codeLength === 6 ? 2 : 1;
    var widthValue = width ? getSizeValueFromProp.getSizeValueFromProp(width, 'rem') : undefined;
    var getLastActiveIndex = function getLastActiveIndex() {
      if (code.length && code.length < codeLength) {
        return code.length;
      }
      var lastEmptyIndex = code.findIndex(function (digit) {
        return digit === '';
      });
      return lastEmptyIndex >= 0 ? lastEmptyIndex : codeLength - 1;
    };
    var handleClick = function handleClick() {
      if (disabled) {
        return;
      }
      var lastActiveIndex = getLastActiveIndex();
      if (inputRefs.current[lastActiveIndex]) {
        inputRefs.current[lastActiveIndex].focus();
      }
    };
    var handleOnKeyDown = function handleOnKeyDown(event, index, type) {
      if (disabled) {
        return;
      }
      var key = event.key;
      if (constants.FORBIDDEN_KEYS.includes(key)) {
        event.preventDefault();
        return;
      }
      if (key === constants.BACKSPACE_KEY) {
        if (index > 0 && code[index] === '') {
          var _inputRefs$current;
          (_inputRefs$current = inputRefs.current[index - 1]) === null || _inputRefs$current === void 0 || _inputRefs$current.focus();
        }
      }
      if (type === 'circle') {
        var _inputRefs$current$in;
        event.preventDefault();
        handleAddSymbol(key, index);
        (_inputRefs$current$in = inputRefs.current[index]) === null || _inputRefs$current$in === void 0 || _inputRefs$current$in.focus();
      }
    };
    var codeSetter = function codeSetter(newCode) {
      setCode(newCode);
      setOriginalValue(newCode.join(''));
      if (onChange) {
        onChange(newCode.join(''));
      }
    };
    var handleChange = function handleChange(event, index) {
      if (disabled) {
        return;
      }
      var rawSymbol = event.currentTarget.value;

      // На мобильных устройствах вставка вызывает onChange по 1 символу
      if (rawSymbol.length > 1) {
        var _inputRefs$current$ac;
        var newCode = _rollupPluginBabelHelpers.toConsumableArray(code);
        var pastedData = (fieldPattern ? rawSymbol.split('').map(function (symb) {
          var _symb$match;
          return ((_symb$match = symb.match(fieldPattern)) === null || _symb$match === void 0 ? void 0 : _symb$match[0]) || '';
        }).filter(Boolean) : rawSymbol.split('')).slice(0, codeLength - index);
        pastedData.forEach(function (element, i) {
          newCode[index + i] = element;
        });
        var activeIndex = Math.min(index + pastedData.length, codeLength - 1);
        (_inputRefs$current$ac = inputRefs.current[activeIndex]) === null || _inputRefs$current$ac === void 0 || _inputRefs$current$ac.focus();
        codeSetter(newCode);
        return;
      }
      var symbol = rawSymbol.charAt(rawSymbol.length - 1);
      handleAddSymbol(symbol, index);
    };
    var handleAddSymbol = function handleAddSymbol(symbol, index) {
      var _inputRefs$current$in2;
      var newCode = _rollupPluginBabelHelpers.toConsumableArray(code);
      (_inputRefs$current$in2 = inputRefs.current[index]) === null || _inputRefs$current$in2 === void 0 || _inputRefs$current$in2.classList.remove(CodeInput_tokens.classes.itemError);
      if (isError) {
        var _captionRef$current;
        (_captionRef$current = captionRef.current) === null || _captionRef$current === void 0 || _captionRef$current.classList.remove(CodeInput_tokens.classes.captionError);
        if (codeErrorBehavior === 'keep') {
          var _inputContainerRef$cu;
          (_inputContainerRef$cu = inputContainerRef.current) === null || _inputContainerRef$cu === void 0 || _inputContainerRef$cu.classList.remove(CodeInput_tokens.classes.codeError, CodeInput_tokens.classes.codeErrorAnimation);
        }
        if (setIsError) {
          setIsError(false);
        }
      }
      if (!fieldPattern) {
        newCode[index] = symbol;
        codeSetter(newCode);
        if (symbol && index < codeLength - 1) {
          var _inputRefs$current2;
          (_inputRefs$current2 = inputRefs.current[index + 1]) === null || _inputRefs$current2 === void 0 || _inputRefs$current2.focus();
        }
        return;
      }
      if (!symbol) {
        newCode[index] = '';
        codeSetter(newCode);
        return;
      }
      if (fieldPattern.test(symbol)) {
        newCode[index] = symbol.charAt(symbol.length - 1);
        codeSetter(newCode);
        if (index < codeLength - 1) {
          var _inputRefs$current3;
          (_inputRefs$current3 = inputRefs.current[index + 1]) === null || _inputRefs$current3 === void 0 || _inputRefs$current3.focus();
        }
      } else {
        newCode[index] = symbol.charAt(symbol.length - 1);
        handleItemError.handleItemError({
          currentSymbol: symbol,
          itemErrorBehavior: itemErrorBehavior,
          index: index,
          newCode: newCode,
          inputRefs: inputRefs,
          inputContainerRef: inputContainerRef,
          codeSetter: codeSetter
        });
      }
    };
    var handlePaste = function handlePaste(event) {
      var _inputRefs$current$ac2;
      var newCode = _rollupPluginBabelHelpers.toConsumableArray(code);
      if (disabled) {
        return;
      }
      event.preventDefault();
      var rawData = event.clipboardData.getData('text/plain');
      var pastedData = (fieldPattern ? rawData.split('').map(function (symb) {
        var _symb$match2;
        return ((_symb$match2 = symb.match(fieldPattern)) === null || _symb$match2 === void 0 ? void 0 : _symb$match2[0]) || '';
      }).filter(Boolean) || [] : rawData.split('')).slice(0, codeLength);
      pastedData.forEach(function (element, index) {
        newCode[index] = element;
      });
      var activeIndex = Math.min(pastedData.length, codeLength - 1);
      (_inputRefs$current$ac2 = inputRefs.current[activeIndex]) === null || _inputRefs$current$ac2 === void 0 || _inputRefs$current$ac2.focus();
      codeSetter(newCode);
    };
    var handleFullCodeEnter = React.useCallback(function (fullCode) {
      if (onFullCodeEnter) {
        onFullCodeEnter(fullCode);
      }
    }, []);
    useCodeHook.useCodeHook({
      inputRefs: inputRefs,
      codeLength: codeLength,
      disabled: disabled,
      autoFocus: autoFocus,
      originalValue: originalValue,
      getLastActiveIndex: getLastActiveIndex,
      handleFullCodeEnter: handleFullCodeEnter
    });
    useDidMountEffect.useDidMountEffect(function () {
      if (isError) {
        handleCodeError.handleCodeError({
          codeLength: codeLength,
          codeErrorBehavior: codeErrorBehavior,
          currentCode: code,
          inputRefs: inputRefs,
          inputContainerRef: inputContainerRef,
          captionRef: captionRef,
          setCode: setCode,
          codeSetter: codeSetter
        });
      }
    }, [isError]);
    return /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      ref: ref,
      view: view,
      size: size,
      disabled: disabled,
      onClick: handleClick,
      className: cls__default.default(className, _rollupPluginBabelHelpers.defineProperty({}, CodeInput_tokens.classes.captionAlignLeft, captionAlign === 'left'))
    }, rest), /*#__PURE__*/React__default.default.createElement(CodeInput_styles.CodeWrapper, {
      ref: inputContainerRef
    }, _rollupPluginBabelHelpers.toConsumableArray(Array(parts)).map(function (_, partIndex) {
      return /*#__PURE__*/React__default.default.createElement(React.Fragment, {
        key: partIndex
      }, /*#__PURE__*/React__default.default.createElement(CodeInput_styles.CodeGroup, {
        role: "group"
      }, _rollupPluginBabelHelpers.toConsumableArray(Array(codeLength / parts)).map(function (_, i) {
        var inputCorrectIndex = i + codeLength / parts * partIndex;
        return /*#__PURE__*/React__default.default.createElement(CodeInput_styles.ItemWrapper, {
          key: String(partIndex + i + partIndex * i)
        }, (!code[inputCorrectIndex] || Boolean(code[inputCorrectIndex]) && hidden) && /*#__PURE__*/React__default.default.createElement(CodeInput_styles.ItemCircle, {
          role: "tab",
          tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
          onKeyDown: function onKeyDown(e) {
            handleOnKeyDown(e, inputCorrectIndex, 'circle');
          },
          className: cls__default.default([Boolean(code[inputCorrectIndex]) && hidden ? CodeInput_tokens.classes.itemCirlceFilled : '', "".concat(CodeInput_tokens.classes.itemCircle, "-").concat(inputCorrectIndex)])
        }), /*#__PURE__*/React__default.default.createElement(CodeInput_styles.ItemInput, _rollupPluginBabelHelpers.extends({
          ref: function ref(element) {
            inputRefs.current[inputCorrectIndex] = element;
          },
          className: cls__default.default(_rollupPluginBabelHelpers.defineProperty({}, CodeInput_tokens.classes.hoverEnabled, inputCorrectIndex >= originalValue.length)),
          hide: hidden,
          inputMode: inputMode,
          value: code[inputCorrectIndex] || '',
          tabIndex: originalValue.length === inputCorrectIndex ? 0 : -1,
          autoComplete: autoComplete,
          onChange: function onChange(e) {
            handleChange(e, inputCorrectIndex);
          },
          onKeyDown: function onKeyDown(e) {
            handleOnKeyDown(e, inputCorrectIndex);
          },
          onPaste: handlePaste
        }, placeholderValue && {
          placeholder: placeholderValue[inputCorrectIndex]
        })));
      })), partIndex !== parts - 1 && (_Separator || (_Separator = /*#__PURE__*/React__default.default.createElement(CodeInput_styles.Separator, null))));
    })), caption && /*#__PURE__*/React__default.default.createElement(CodeInput_styles.CaptionWrapper, {
      ref: captionRef,
      captionAlign: captionAlign,
      widthValue: widthValue
    }, caption));
  });
};
var codeInputConfig = {
  name: 'CodeInput',
  tag: 'div',
  layout: codeInputRoot,
  base: CodeInput_styles.base,
  variations: {
    view: {
      css: base.base
    },
    size: {
      css: base$1.base
    },
    disabled: {
      css: base$2.base,
      attrs: true
    }
  },
  defaults: {
    size: 'm',
    view: 'default'
  }
};

exports.codeInputConfig = codeInputConfig;
exports.codeInputRoot = codeInputRoot;
