import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useCallback, useRef } from 'react';
import styled, { css } from 'styled-components';
import { useConsolidatedRef, useElement, useFocusWithin, useI18n, useInputFormatter, useTestIds } from '../../hooks';
import { defaultThemeProp } from '../../theme';
import FormField from '../FormField';
import { StyledFormControl } from '../FormControl';
import StyledInput from '../Input/Input.styles';
import Select, { Option } from '../Select';
import Input from '../Input';
import { StyledSelect } from '../Select/Select';
import Flex from '../Flex';
import { withTestIds, createClassName } from '../../utils';
import Tooltip from '../Tooltip';
import callingCodes from './callingCodes';
import { convertToCallbackParameter, formatPhone, formatPhoneNumber, getPhoneNumberParts } from './utils';
import { getPhoneInputTestIds } from './Phone.test-ids';
const StyledPhoneInput = styled.div(() => {
    return css `
    border: 0;

    > ${StyledSelect} {
      max-width: max-content;
      border-inline-end: none;
      border-start-end-radius: 0;
      border-end-end-radius: 0;
    }

    > ${StyledSelect} + ${StyledInput} {
      border-start-start-radius: 0;
      border-end-start-radius: 0;
    }

    ${StyledSelect},
    ${StyledInput} {
      &:focus {
        z-index: 1;
      }
    }
  `;
});
StyledPhoneInput.defaultProps = defaultThemeProp;
const PhoneInput = forwardRef(function PhoneInput(props, ref) {
    const { testId, value, id, label, labelHidden, info, status, required, readOnly, disabled, showCountryCode = false, callingCodesList = callingCodes, onChange, onBlur, onFocus, onResolveSuggestion, additionalInfo, className, ...restProps } = props;
    const testIds = useTestIds(testId, getPhoneInputTestIds);
    const [selectEl, setSelectEl] = useElement();
    const [inputEl, setInputEl] = useElement();
    const t = useI18n();
    const [countryCode = callingCodesList[0], subscriberNumber = ''] = value
        ? getPhoneNumberParts(value, callingCodesList)
        : [];
    const onFocusChange = (focused) => {
        const callbackParam = convertToCallbackParameter(countryCode, subscriberNumber);
        if (focused)
            onFocus?.(callbackParam);
        else
            onBlur?.(callbackParam);
    };
    const onInputChange = (e) => {
        onChange?.(convertToCallbackParameter(countryCode, e.target.value));
    };
    const onSelectChange = (e) => {
        onChange?.(convertToCallbackParameter(e.target.value, subscriberNumber));
    };
    const inputRef = useConsolidatedRef(ref, setInputEl);
    const containerRef = useRef(null);
    useFocusWithin([containerRef], onFocusChange);
    const formatter = useCallback((number) => {
        if (value && readOnly && showCountryCode) {
            const temp = formatPhone(value, { nationalFormat: !readOnly });
            if (temp)
                return temp;
        }
        return formatPhoneNumber(number.replace(/\D+/g, ''), countryCode);
    }, [readOnly, countryCode, showCountryCode]);
    const formatted = useInputFormatter(inputRef, subscriberNumber, formatter);
    const codesOptions = (_jsx(_Fragment, { children: callingCodesList.map(code => (_jsx(Option, { value: code, children: code }, code))) }));
    const Comp = (_jsxs(StyledPhoneInput, { "data-testid": testIds.root, as: StyledFormControl, forwardedAs: Flex, container: { alignItems: 'center', wrap: 'nowrap' }, ref: containerRef, status: status, readOnly: readOnly, disabled: disabled, children: [showCountryCode && !readOnly && (_jsxs(_Fragment, { children: [_jsx(Select, { "data-testid": testIds.countryCode, value: countryCode, "aria-label": t('select_country_code'), onChange: onSelectChange, required: required, status: status, readOnly: readOnly, disabled: disabled, autoComplete: 'tel-country-code', ref: setSelectEl, hasSuggestion: status === 'pending' && !!onResolveSuggestion, children: codesOptions }), selectEl && (_jsx(Tooltip, { target: selectEl, describeTarget: false, showDelay: 'none', hideDelay: 'none', children: t('country_code') }))] })), _jsx(Input, { "data-testid": testIds.control, ...restProps, inputMode: 'tel', ref: inputRef, value: formatted, "aria-label": t('enter_a_number'), onChange: onInputChange, required: required, status: status, readOnly: readOnly, disabled: disabled, autoComplete: 'tel-national', onResolveSuggestion: onResolveSuggestion, className: createClassName('phone-input', className) }), showCountryCode && inputEl && (_jsx(Tooltip, { target: inputEl, describeTarget: false, showDelay: 'none', hideDelay: 'none', children: t('phone_number') }))] }));
    return label ? (_jsx(FormField, { testId: testIds, as: 'fieldset', labelAs: 'legend', additionalInfo: additionalInfo, label: label, labelHidden: labelHidden, id: id, info: info, status: status, required: required, disabled: disabled, onResolveSuggestion: onResolveSuggestion, children: Comp })) : (Comp);
});
export default withTestIds(PhoneInput, getPhoneInputTestIds);
//# sourceMappingURL=PhoneInput.js.map