"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Phone = void 0;
var _propOr2 = _interopRequireDefault(require("ramda/src/propOr"));
var _react = _interopRequireWildcard(require("react"));
var _ = require("../../..");
var _context = require("../Select/lib/context");
var _CountryCodeLabel = require("./CountryCodeLabel");
var _Phone = require("./Phone.styled");
var _utils = require("../../../common/utils");
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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
var hasError = function hasError(error) {
  return error && error !== '';
};
var components = {
  StyledInput: _Phone.StyledInput
};
var doNothing = function doNothing() {};
var PhoneComponent = _react.default.forwardRef(function (props, ref) {
  var _defaultValue$phoneNu;
  var autoComplete = props.autoComplete,
    autoFocus = props.autoFocus,
    defaultValue = props.defaultValue,
    disabled = props.disabled,
    error = props.error,
    id = props.id,
    maxLength = props.maxLength,
    name = props.name,
    _props$onBlur = props.onBlur,
    onBlur = _props$onBlur === void 0 ? doNothing : _props$onBlur,
    _props$onChange = props.onChange,
    onChange = _props$onChange === void 0 ? doNothing : _props$onChange,
    onClick = props.onClick,
    _props$onFocus = props.onFocus,
    onFocus = _props$onFocus === void 0 ? doNothing : _props$onFocus,
    onMouseLeave = props.onMouseLeave,
    onKeyDown = props.onKeyDown,
    onKeyPress = props.onKeyPress,
    onKeyUp = props.onKeyUp,
    placeholder = props.placeholder,
    required = props.required,
    _props$variant = props.variant,
    variant = _props$variant === void 0 ? 'normal' : _props$variant,
    size = props.size,
    success = props.success,
    visuallyEmphasiseRequired = props.visuallyEmphasiseRequired,
    type = props.type,
    sortByCountry = props.sortByCountry,
    _props$disableSearchC = props.disableSearchComponent,
    disableSearchComponent = _props$disableSearchC === void 0 ? true : _props$disableSearchC;
  var options = (0, _react.useMemo)(function () {
    return [{
      label: _react.default.createElement(_CountryCodeLabel.CountryCodeLabel, {
        countryCode: "dk",
        prefixCode: "+45"
      }),
      value: '45',
      country: 'dk',
      flag: _react.default.createElement(_.Flag, {
        country: "dk",
        size: "s"
      })
    }, {
      label: _react.default.createElement(_CountryCodeLabel.CountryCodeLabel, {
        countryCode: "se",
        prefixCode: "+46"
      }),
      value: '46',
      country: 'se',
      flag: _react.default.createElement(_.Flag, {
        country: "se",
        size: "s"
      })
    }, {
      label: _react.default.createElement(_CountryCodeLabel.CountryCodeLabel, {
        countryCode: "no",
        prefixCode: "+47"
      }),
      value: '47',
      country: 'no',
      flag: _react.default.createElement(_.Flag, {
        country: "no",
        size: "s"
      })
    }, {
      label: _react.default.createElement(_CountryCodeLabel.CountryCodeLabel, {
        countryCode: "fi",
        prefixCode: "+358"
      }),
      value: '358',
      country: 'fi',
      flag: _react.default.createElement(_.Flag, {
        country: "fi",
        size: "s"
      })
    }, {
      label: _react.default.createElement(_.Flexbox, {
        container: true,
        alignItems: "center",
        gap: 3
      }, _react.default.createElement(_.Flexbox, {
        item: true
      }, _react.default.createElement(_.OldIcon.Globe, {
        size: 3
      })), _react.default.createElement(_.Flexbox, {
        item: true
      }, _react.default.createElement(_.Typography, {
        type: "secondary"
      }, "+"))),
      value: '',
      country: 'other',
      flag: _react.default.createElement(_.OldIcon.Globe, {
        size: 3
      })
    }];
  }, []);
  var byCountry = (0, _react.useCallback)(function (a, b) {
    if (a.country === sortByCountry) {
      return -1;
    }
    if (b.country === sortByCountry) {
      return 1;
    }
    return 0;
  }, [sortByCountry]);
  var sortedOptions = (0, _react.useMemo)(function () {
    return options.sort(byCountry);
  }, [options, byCountry]);
  var getInitialCountryCodeValue = (0, _react.useCallback)(function () {
    if (defaultValue !== null && defaultValue !== void 0 && defaultValue.countryCode) {
      return options.filter(function (opt) {
        return opt.value === defaultValue.countryCode.replace('+', '');
      });
    }
    return sortByCountry ? [sortedOptions[0]] : [options[0]];
  }, [defaultValue, options, sortByCountry, sortedOptions]);
  var CountryCodeListItem = function CountryCodeListItem(_ref) {
    var index = _ref.index;
    var _useSelectMachineFrom = (0, _context.useSelectMachineFromContext)(),
      _useSelectMachineFrom2 = _slicedToArray(_useSelectMachineFrom, 1),
      state = _useSelectMachineFrom2[0];
    var option = state.context.options[index];
    var isKeyboardNavigation = state.matches('interaction.enabled.active.navigation.keyboard');
    var focused = isKeyboardNavigation && state.context.itemFocusIdx === index;
    return _react.default.createElement(_Phone.StyledBox, {
      px: 2,
      py: 1,
      focused: focused,
      isKeyboardNavigation: isKeyboardNavigation
    }, _react.default.createElement(_.Flexbox, {
      container: true,
      width: "100%"
    }, option.label));
  };
  var CountryCodeValue = function CountryCodeValue() {
    var _useSelectMachineFrom3 = (0, _context.useSelectMachineFromContext)(),
      _useSelectMachineFrom4 = _slicedToArray(_useSelectMachineFrom3, 1),
      state = _useSelectMachineFrom4[0];
    var selectedOption = state.context.selectedItems.length === 0 ? null : state.context.selectedItems[0];
    return selectedOption && _react.default.createElement(_.Flexbox, {
      container: true,
      alignItems: "center",
      justifyContent: "center"
    }, _react.default.createElement(_.Box, {
      pl: 2
    }, selectedOption.flag));
  };
  var _useState = (0, _react.useState)(getInitialCountryCodeValue()),
    _useState2 = _slicedToArray(_useState, 2),
    countryCode = _useState2[0],
    setCountryCode = _useState2[1];
  var _useState3 = (0, _react.useState)((_defaultValue$phoneNu = defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.phoneNumber) !== null && _defaultValue$phoneNu !== void 0 ? _defaultValue$phoneNu : ''),
    _useState4 = _slicedToArray(_useState3, 2),
    phoneNumber = _useState4[0],
    setPhoneNumber = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = _slicedToArray(_useState5, 2),
    focused = _useState6[0],
    setFocused = _useState6[1];
  var changeCountryCode = function changeCountryCode(vals) {
    var newValue = vals[0].value;
    setCountryCode(vals);
    onChange("+".concat(newValue).concat(phoneNumber), newValue, phoneNumber);
  };
  var changePhoneNumber = function changePhoneNumber(e) {
    var newValue = e.target.value;
    setPhoneNumber(newValue);
    onChange("+".concat(countryCode[0].value).concat(newValue), countryCode[0].value, newValue);
  };
  var fieldRef = (0, _react.useRef)(null);
  var handleClickOutside = (0, _react.useCallback)(function (e) {
    var field = (0, _propOr2.default)(null, 'current', fieldRef);
    if (focused && field && !field.contains(e.target)) {
      onBlur(e);
      setFocused(false);
    }
  }, [fieldRef, onBlur, focused]);
  var handleFocus = (0, _react.useCallback)(function (e) {
    if (focused) {
      return;
    }
    setFocused(true);
    onFocus(e);
  }, [onFocus, focused]);
  (0, _react.useEffect)(function () {
    document.addEventListener('mousedown', handleClickOutside);
    return function () {
      return document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [handleClickOutside]);
  return _react.default.createElement(_.FormField, {
    error: error,
    extraInfo: props.extraInfo,
    hideLabel: props.hideLabel,
    label: props.label,
    labelTooltip: props.labelTooltip,
    labelTooltipPosition: props.labelTooltipPosition,
    labelTooltipInModal: props.labelTooltipInModal,
    className: props.className,
    width: props.width,
    disabled: disabled,
    required: visuallyEmphasiseRequired,
    ref: fieldRef
  }, _react.default.createElement(_Phone.StyledWrapper, {
    container: true,
    alignItems: "center",
    $disabled: disabled,
    $error: error,
    $focused: focused,
    $size: size,
    $success: success,
    $variant: variant
  }, _react.default.createElement(_Phone.StyledSelect, {
    label: "country code",
    hideLabel: true,
    height: size === 's' ? 7.5 : 9.5,
    disabled: disabled,
    options: sortByCountry ? sortedOptions : options,
    components: {
      ListItem: CountryCodeListItem,
      SelectedValue: CountryCodeValue
    },
    value: countryCode,
    onChange: changeCountryCode,
    listWidth: "80px",
    id: "phone-input-country-code-selector",
    onFocus: handleFocus,
    disableSearchComponent: disableSearchComponent
  }), _react.default.createElement(_Phone.StyledCountryCode, {
    container: true,
    alignItems: "center",
    disabled: disabled
  }, _react.default.createElement(_.Typography, {
    type: "secondary",
    color: function color(t) {
      return t.color[disabled ? 'label' : 'text'];
    }
  }, "+", countryCode[0].value)), _react.default.createElement(_.Flexbox, {
    container: true,
    alignItems: "center",
    width: "100%"
  }, _react.default.createElement(_Phone.StyledTypography, {
    type: "secondary"
  }, _react.default.createElement(_Phone.StyledInput, _extends({
    $error: error,
    $variant: variant,
    $size: size,
    $success: success,
    onChange: changePhoneNumber,
    defaultValue: defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.phoneNumber,
    autoComplete: autoComplete,
    autoFocus: autoFocus,
    disabled: disabled,
    id: id,
    maxLength: maxLength,
    name: name,
    onClick: onClick,
    onMouseLeave: onMouseLeave,
    onKeyDown: onKeyDown,
    onKeyPress: onKeyPress,
    onKeyUp: onKeyUp,
    placeholder: placeholder,
    required: required,
    type: type,
    ref: ref,
    onFocus: handleFocus
  }, (0, _utils.getAriaProps)(props), (0, _utils.getDataProps)(props), hasError(error) ? {
    'aria-invalid': true
  } : {}))))));
});
var Phone = exports.Phone = PhoneComponent;
Phone.components = components;