"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("./EnhancedPhoneNumberField.global.scss");
const hooks_1 = require("../../../../hooks/index.js");
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const Translation_1 = require("translations/Translation");
const Icon_1 = __importStar(require("../../Icon/Icon"));
const AutoFocusOnSelect_1 = require("../../../../hooks/AutoFocusOnSelect");
const CountryCodesAndNumbers_1 = require("../../../../models/CountryCodesAndNumbers");
const Select_1 = require("../../Select/Select");
const PHONE_AND_PREFIX_SPLIT = ' ';
const EnhancedPhoneNumberField = (props, ref) => {
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const innerRef = (0, react_1.useRef)(null);
    (0, react_1.useImperativeHandle)(ref, () => innerRef.current);
    const { onDropdownClosed, onItemSelected, onTriggerClicked, isDropdownOpen, isFocused } = (0, AutoFocusOnSelect_1.useAutoFocusOnSelect)({
        ref: innerRef.current,
        onlyAutoOpenWhenInputEmpty: true,
        disableOpenOnFocus: true,
    });
    const { t } = (0, react_i18next_1.useTranslation)();
    const organizedCountries = (0, react_1.useMemo)(() => {
        return CountryCodesAndNumbers_1.ListOfCountriesAndCodes.sort((a, b) => {
            return `${(a.suggested ? '000' : '') + a.label}`.localeCompare(`${(b.suggested ? '000' : '') + b.label}`);
        });
    }, [CountryCodesAndNumbers_1.ListOfCountriesAndCodes]);
    const [container, setContainer] = (0, react_1.useState)(null);
    const { validationStatus, name, onChange, value } = props;
    const [selectedCountry, subscriberCode] = (0, react_1.useMemo)(() => {
        var _a, _b;
        const defaultCountryCode = (hotel === null || hotel === void 0 ? void 0 : hotel.countryCode) || organizedCountries[0].phone;
        const [prefix, number] = (_a = value === null || value === void 0 ? void 0 : value.split(PHONE_AND_PREFIX_SPLIT)) !== null && _a !== void 0 ? _a : [];
        const codeToFind = prefix || defaultCountryCode;
        const selectedCountry = (_b = organizedCountries.find(({ phone }) => phone === codeToFind)) !== null && _b !== void 0 ? _b : organizedCountries[0];
        return [selectedCountry, number !== null && number !== void 0 ? number : ''];
    }, [value, organizedCountries, hotel === null || hotel === void 0 ? void 0 : hotel.countryCode]);
    const getOption = (key) => {
        return organizedCountries.find(({ code }) => code === key);
    };
    const raiseOnChangeEvent = (prefix, suffix) => {
        var _a;
        let newSuffix = suffix !== null && suffix !== void 0 ? suffix : subscriberCode;
        if (newSuffix.startsWith('0')) {
            newSuffix = newSuffix.substring(1);
        }
        const newValue = `${(_a = prefix === null || prefix === void 0 ? void 0 : prefix.phone) !== null && _a !== void 0 ? _a : selectedCountry.phone}${PHONE_AND_PREFIX_SPLIT}${newSuffix}`;
        if (value != newValue) {
            onChange === null || onChange === void 0 ? void 0 : onChange({ target: { name, value: newValue } });
        }
    };
    const onInputChanged = (e) => {
        const value = e.target.value;
        raiseOnChangeEvent(undefined, value);
    };
    const onPrefixChanged = (selectedCountry) => {
        onItemSelected();
        raiseOnChangeEvent(selectedCountry, undefined);
    };
    const fieldClasses = (0, classnames_1.default)('rs-enhanced-phone-field', {
        [`--${validationStatus}`]: !!validationStatus,
        '--focused': isFocused,
        '--disabled': props.disabled,
    });
    const onCountryClick = (country) => {
        onPrefixChanged(country);
        return;
    };
    return (react_1.default.createElement("div", { className: fieldClasses },
        react_1.default.createElement("div", { className: "rs-enhanced-phone-field--country", onClick: onTriggerClicked },
            react_1.default.createElement("div", { className: "rs-enhanced-phone-field--country-icon" }, (0, CountryCodesAndNumbers_1.convertCountryCodeToFlag)(selectedCountry.code)),
            react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.Dropdown })),
        react_1.default.createElement("div", { className: "rs-enhanced-phone-field--number" },
            react_1.default.createElement("span", { className: "rs-enhanced-phone-field--number-prefix" },
                "+",
                selectedCountry.phone),
            react_1.default.createElement("input", { disabled: props.disabled, ref: innerRef, placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.Phone) + ' *', type: "number", style: { paddingLeft: selectedCountry.phone.length * 8 + 20 + 'px' }, onChange: onInputChanged, value: subscriberCode }),
            react_1.default.createElement("div", { className: "rs-enhanced-phone-field--number-status" })),
        react_1.default.createElement("div", { className: "rs-enhanced-phone-field--anchor", ref: setContainer }),
        react_1.default.createElement(Select_1.Select, { open: isDropdownOpen, onClose: onDropdownClosed, target: container, options: organizedCountries, value: selectedCountry.code, onChange: (value) => onCountryClick(getOption(value)), labelName: "code", keyName: "code", renderOption: (country) => (react_1.default.createElement("div", { className: "rs-enhanced-phone-field--suggest-list-country" },
                react_1.default.createElement("div", { className: "rs-enhanced-phone-field--suggest-list-country-icon" }, (0, CountryCodesAndNumbers_1.convertCountryCodeToFlag)(country === null || country === void 0 ? void 0 : country.code)),
                react_1.default.createElement("div", { className: "rs-enhanced-phone-field--suggest-list-country-name" }, country === null || country === void 0 ? void 0 :
                    country.label,
                    " ",
                    react_1.default.createElement("span", null,
                        "+", country === null || country === void 0 ? void 0 :
                        country.phone)))) })));
};
exports.default = react_1.default.forwardRef(EnhancedPhoneNumberField);
//# sourceMappingURL=EnhancedPhoneNumberField.js.map