import _propOr from "ramda/src/propOr";
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; }
import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react';
import { Box, Flag, Flexbox, FormField, OldIcon, Typography } from '../../..';
import { useSelectMachineFromContext } from '../Select/lib/context';
import { CountryCodeLabel } from './CountryCodeLabel';
import { StyledSelect, StyledCountryCode, StyledInput, StyledWrapper, StyledBox, StyledTypography } from './Phone.styled';
import { getAriaProps, getDataProps } from '../../../common/utils';
var hasError = function hasError(error) {
  return error && error !== '';
};
var components = {
  StyledInput: StyledInput
};
var doNothing = function doNothing() {};
var PhoneComponent = React.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 = useMemo(function () {
    return [{
      label: React.createElement(CountryCodeLabel, {
        countryCode: "dk",
        prefixCode: "+45"
      }),
      value: '45',
      country: 'dk',
      flag: React.createElement(Flag, {
        country: "dk",
        size: "s"
      })
    }, {
      label: React.createElement(CountryCodeLabel, {
        countryCode: "se",
        prefixCode: "+46"
      }),
      value: '46',
      country: 'se',
      flag: React.createElement(Flag, {
        country: "se",
        size: "s"
      })
    }, {
      label: React.createElement(CountryCodeLabel, {
        countryCode: "no",
        prefixCode: "+47"
      }),
      value: '47',
      country: 'no',
      flag: React.createElement(Flag, {
        country: "no",
        size: "s"
      })
    }, {
      label: React.createElement(CountryCodeLabel, {
        countryCode: "fi",
        prefixCode: "+358"
      }),
      value: '358',
      country: 'fi',
      flag: React.createElement(Flag, {
        country: "fi",
        size: "s"
      })
    }, {
      label: React.createElement(Flexbox, {
        container: true,
        alignItems: "center",
        gap: 3
      }, React.createElement(Flexbox, {
        item: true
      }, React.createElement(OldIcon.Globe, {
        size: 3
      })), React.createElement(Flexbox, {
        item: true
      }, React.createElement(Typography, {
        type: "secondary"
      }, "+"))),
      value: '',
      country: 'other',
      flag: React.createElement(OldIcon.Globe, {
        size: 3
      })
    }];
  }, []);
  var byCountry = useCallback(function (a, b) {
    if (a.country === sortByCountry) {
      return -1;
    }
    if (b.country === sortByCountry) {
      return 1;
    }
    return 0;
  }, [sortByCountry]);
  var sortedOptions = useMemo(function () {
    return options.sort(byCountry);
  }, [options, byCountry]);
  var getInitialCountryCodeValue = 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 = 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.createElement(StyledBox, {
      px: 2,
      py: 1,
      focused: focused,
      isKeyboardNavigation: isKeyboardNavigation
    }, React.createElement(Flexbox, {
      container: true,
      width: "100%"
    }, option.label));
  };
  var CountryCodeValue = function CountryCodeValue() {
    var _useSelectMachineFrom3 = useSelectMachineFromContext(),
      _useSelectMachineFrom4 = _slicedToArray(_useSelectMachineFrom3, 1),
      state = _useSelectMachineFrom4[0];
    var selectedOption = state.context.selectedItems.length === 0 ? null : state.context.selectedItems[0];
    return selectedOption && React.createElement(Flexbox, {
      container: true,
      alignItems: "center",
      justifyContent: "center"
    }, React.createElement(Box, {
      pl: 2
    }, selectedOption.flag));
  };
  var _useState = useState(getInitialCountryCodeValue()),
    _useState2 = _slicedToArray(_useState, 2),
    countryCode = _useState2[0],
    setCountryCode = _useState2[1];
  var _useState3 = 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 = 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 = useRef(null);
  var handleClickOutside = useCallback(function (e) {
    var field = _propOr(null, 'current', fieldRef);
    if (focused && field && !field.contains(e.target)) {
      onBlur(e);
      setFocused(false);
    }
  }, [fieldRef, onBlur, focused]);
  var handleFocus = useCallback(function (e) {
    if (focused) {
      return;
    }
    setFocused(true);
    onFocus(e);
  }, [onFocus, focused]);
  useEffect(function () {
    document.addEventListener('mousedown', handleClickOutside);
    return function () {
      return document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [handleClickOutside]);
  return React.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.createElement(StyledWrapper, {
    container: true,
    alignItems: "center",
    $disabled: disabled,
    $error: error,
    $focused: focused,
    $size: size,
    $success: success,
    $variant: variant
  }, React.createElement(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.createElement(StyledCountryCode, {
    container: true,
    alignItems: "center",
    disabled: disabled
  }, React.createElement(Typography, {
    type: "secondary",
    color: function color(t) {
      return t.color[disabled ? 'label' : 'text'];
    }
  }, "+", countryCode[0].value)), React.createElement(Flexbox, {
    container: true,
    alignItems: "center",
    width: "100%"
  }, React.createElement(StyledTypography, {
    type: "secondary"
  }, React.createElement(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
  }, getAriaProps(props), getDataProps(props), hasError(error) ? {
    'aria-invalid': true
  } : {}))))));
});
export var Phone = PhoneComponent;
Phone.components = components;