"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InputPhone = void 0;
var _react = _interopRequireWildcard(require("react"));
var _countryExplorer = require("country-explorer");
var _Input = require("./Input");
var _InputSelect = require("./InputSelect");
var _Styles = require("./Styles");
var _utils = require("../../utils");
var _RadioButton = require("../RadioButton");
var _excluded = ["size", "disabled", "value", "onChange", "defaultCountry"];
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var renderOption = function renderOption(option, data) {
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Styles.StyledOptionWrapper, null, /*#__PURE__*/_react.default.createElement(_Styles.StyledOptionFlag, null, (0, _countryExplorer.getCountryFlag)(option.id)), /*#__PURE__*/_react.default.createElement(_Styles.StyledOptionName, null, option.name)), /*#__PURE__*/_react.default.createElement(_RadioButton.RadioButton, {
    checked: data.checked,
    onChange: data.onChange
  }));
};
var InputPhone = exports.InputPhone = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var _ref$size = _ref.size,
    size = _ref$size === void 0 ? "regular" : _ref$size,
    disabled = _ref.disabled,
    _ref$value = _ref.value,
    defaultValue = _ref$value === void 0 ? "" : _ref$value,
    onChange = _ref.onChange,
    _ref$defaultCountry = _ref.defaultCountry,
    defaultCountry = _ref$defaultCountry === void 0 ? "US" : _ref$defaultCountry,
    rest = _objectWithoutProperties(_ref, _excluded);
  var inputRef = (0, _react.useRef)(null);
  var handleRef = (0, _utils.useForkRef)(ref, inputRef);
  var _useState = (0, _react.useState)(defaultCountry),
    _useState2 = _slicedToArray(_useState, 2),
    prefix = _useState2[0],
    setPrefix = _useState2[1];
  var _useState3 = (0, _react.useState)(""),
    _useState4 = _slicedToArray(_useState3, 2),
    value = _useState4[0],
    setValue = _useState4[1];
  var options = _countryExplorer.countriesArraySortedByName.map(function (country) {
    return {
      id: country.countryCode,
      name: "+".concat(country.callingCode, " ").concat(country.name)
    };
  });
  var separatePrefixFromValue = function separatePrefixFromValue(fullValue) {
    var newPrefix = prefix;
    var newValue = fullValue;
    if (fullValue.startsWith("+") || fullValue.startsWith("00")) {
      var prefixLength = fullValue.startsWith("+") ? 1 : 2;
      var digits = fullValue.slice(prefixLength);
      for (var i = digits.length; i >= 1; i--) {
        var code = digits.slice(0, i);
        if (_countryExplorer.callingCodeToCountryCodeMap[code]) {
          newPrefix = _countryExplorer.callingCodeToCountryCodeMap[code];
          newValue = fullValue.slice(prefixLength + (0, _countryExplorer.getCountryCallingCode)(newPrefix).length);
          break;
        }
      }
    } else if (fullValue.startsWith(prefix)) {
      newValue = fullValue.slice(prefix.length);
    }
    return {
      newPrefix,
      newValue
    };
  };
  (0, _react.useEffect)(function () {
    var _separatePrefixFromVa = separatePrefixFromValue(defaultValue),
      newPrefix = _separatePrefixFromVa.newPrefix,
      newValue = _separatePrefixFromVa.newValue;
    setPrefix(newPrefix);
    setValue(newValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultValue]);
  var handleChange = (0, _react.useCallback)(function (e) {
    var inputValue = e.target.value;
    if (/[^0-9+]/.test(inputValue)) {
      return;
    }
    var _separatePrefixFromVa2 = separatePrefixFromValue(inputValue),
      newPrefix = _separatePrefixFromVa2.newPrefix,
      newValue = _separatePrefixFromVa2.newValue;
    setPrefix(newPrefix);
    setValue(newValue);
    typeof onChange === "function" && onChange("+".concat((0, _countryExplorer.getCountryCallingCode)(newPrefix)).concat(newValue));
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [onChange, prefix]);
  var handleSelectChange = function handleSelectChange(val) {
    setPrefix(val);
    setTimeout(function () {
      var _inputRef$current;
      (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 || _inputRef$current.focus();
    }, 200);
    typeof onChange === "function" && onChange("+".concat((0, _countryExplorer.getCountryCallingCode)(val)).concat(value));
  };
  var handlePaste = function handlePaste(e) {
    e.preventDefault();
    var paste = e.clipboardData.getData("text");
    var filteredPaste = paste.replace(/[^0-9+]/g, "");
    var inputElement = e.currentTarget;
    var selectionStart = inputElement.selectionStart,
      selectionEnd = inputElement.selectionEnd;
    if (selectionStart !== null && selectionEnd !== null) {
      var currentValue = inputElement.value;
      var beforeSelection = currentValue.slice(0, selectionStart);
      var afterSelection = currentValue.slice(selectionEnd);
      var newValueAfterPaste = beforeSelection + filteredPaste + afterSelection;
      var _separatePrefixFromVa3 = separatePrefixFromValue(newValueAfterPaste),
        newPrefix = _separatePrefixFromVa3.newPrefix,
        newValue = _separatePrefixFromVa3.newValue;
      setPrefix(newPrefix);
      setValue(newValue);
      typeof onChange === "function" && onChange("+".concat((0, _countryExplorer.getCountryCallingCode)(newPrefix)).concat(newValue));
    }
  };
  return /*#__PURE__*/_react.default.createElement(_Input.Input, _extends({}, rest, {
    ref: handleRef,
    size: size,
    value: value,
    disabled: disabled,
    type: "text",
    onPaste: handlePaste,
    onChange: handleChange,
    "data-testid": "InputPhone",
    startAdornment: /*#__PURE__*/_react.default.createElement(_InputSelect.InputSelect, {
      size: size,
      onChange: handleSelectChange,
      options: options,
      selected: prefix,
      selectedLabel: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Styles.StyledFlagTriggerLabel, {
        $size: size
      }, (0, _countryExplorer.getCountryFlag)(prefix)), "+", (0, _countryExplorer.getCountryCallingCode)(prefix)),
      disabled: disabled,
      keepSameOptionsOrder: false,
      search: true,
      renderOption: renderOption
    })
  }));
});
InputPhone.displayName = "InputPhone";
//# sourceMappingURL=InputPhone.js.map