import _extends from "@babel/runtime/helpers/esm/extends";
import React, { forwardRef, useCallback, useEffect, useRef, useState } from "react";
import { callingCodeToCountryCodeMap, countriesArraySortedByName, getCountryCallingCode, getCountryFlag } from "country-explorer";
import { Input } from "./Input";
import { InputSelect } from "./InputSelect";
import { StyledFlagTriggerLabel, StyledOptionCode, StyledOptionFlag, StyledOptionName, StyledOptionRowEnd, StyledOptionWrapper } from "./Styles";
import { useForkRef } from "../../utils";
import { RadioButton } from "../RadioButton";
const renderOption = (option, data) => /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledOptionWrapper, null, /*#__PURE__*/React.createElement(StyledOptionFlag, null, getCountryFlag(option.id)), /*#__PURE__*/React.createElement(StyledOptionName, null, option.name)), /*#__PURE__*/React.createElement(StyledOptionRowEnd, null, /*#__PURE__*/React.createElement(StyledOptionCode, null, option.additionalInfo), /*#__PURE__*/React.createElement(RadioButton, {
  checked: data.checked,
  onChange: data.onChange
})));
export const InputPhone = /*#__PURE__*/forwardRef((_ref, ref) => {
  let {
    size = "regular",
    disabled,
    value: defaultValue = "",
    onChange,
    defaultCountry = "US",
    ...rest
  } = _ref;
  const inputRef = useRef(null);
  const handleRef = useForkRef(ref, inputRef);
  const [prefix, setPrefix] = useState(defaultCountry);
  const [value, setValue] = useState("");
  const options = countriesArraySortedByName.map(country => ({
    id: country.countryCode,
    name: country.name,
    additionalInfo: "+" + country.callingCode
  }));
  const separatePrefixFromValue = fullValue => {
    let newPrefix = prefix;
    let newValue = fullValue;
    if (fullValue.startsWith("+") || fullValue.startsWith("00")) {
      const prefixLength = fullValue.startsWith("+") ? 1 : 2;
      const digits = fullValue.slice(prefixLength);
      for (let i = digits.length; i >= 1; i--) {
        const code = digits.slice(0, i);
        if (callingCodeToCountryCodeMap[code]) {
          newPrefix = callingCodeToCountryCodeMap[code];
          const dialCode = getCountryCallingCode(newPrefix);
          newValue = fullValue.slice(prefixLength + dialCode.length);
          break;
        }
      }
    }
    return {
      newPrefix,
      newValue
    };
  };
  useEffect(() => {
    const {
      newPrefix,
      newValue
    } = separatePrefixFromValue(defaultValue);
    setPrefix(newPrefix);
    setValue(newValue);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultValue]);
  const handleChange = useCallback(e => {
    const inputValue = e.target.value;
    if (/[^0-9+]/.test(inputValue)) {
      return;
    }
    const {
      newPrefix,
      newValue
    } = separatePrefixFromValue(inputValue);
    setPrefix(newPrefix);
    setValue(newValue);
    typeof onChange === "function" && onChange("+" + getCountryCallingCode(newPrefix) + newValue);
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [onChange, prefix]);
  const handleSelectChange = val => {
    setPrefix(val);
    setTimeout(() => {
      var _inputRef$current;
      (_inputRef$current = inputRef.current) == null || _inputRef$current.focus();
    }, 200);
    typeof onChange === "function" && onChange("+" + getCountryCallingCode(val) + value);
  };
  const handlePaste = e => {
    e.preventDefault();
    const paste = e.clipboardData.getData("text");
    const filteredPaste = paste.replace(/[^0-9+]/g, "");
    const inputElement = e.currentTarget;
    const {
      selectionStart,
      selectionEnd
    } = inputElement;
    if (selectionStart !== null && selectionEnd !== null) {
      const currentValue = inputElement.value;
      const beforeSelection = currentValue.slice(0, selectionStart);
      const afterSelection = currentValue.slice(selectionEnd);
      const newValueAfterPaste = beforeSelection + filteredPaste + afterSelection;
      const {
        newPrefix,
        newValue
      } = separatePrefixFromValue(newValueAfterPaste);
      setPrefix(newPrefix);
      setValue(newValue);
      typeof onChange === "function" && onChange("+" + getCountryCallingCode(newPrefix) + newValue);
    }
  };
  return /*#__PURE__*/React.createElement(Input, _extends({}, rest, {
    ref: handleRef,
    size: size,
    value: value,
    disabled: disabled,
    type: "text",
    onPaste: handlePaste,
    onChange: handleChange,
    "data-testid": "InputPhone",
    startAdornment: /*#__PURE__*/React.createElement(InputSelect, {
      size: size,
      onChange: handleSelectChange,
      options: options,
      selected: prefix,
      filterCriteria: (option, filter) => {
        var _option$additionalInf;
        return !!(option != null && (_option$additionalInf = option.additionalInfo) != null && _option$additionalInf.toLowerCase().includes(filter));
      },
      selectedLabel: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledFlagTriggerLabel, {
        $size: size
      }, getCountryFlag(prefix)), "+", getCountryCallingCode(prefix)),
      disabled: disabled,
      keepSameOptionsOrder: false,
      search: true,
      renderOption: renderOption
    })
  }));
});
InputPhone.displayName = "InputPhone";
//# sourceMappingURL=InputPhone.js.map