"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("./StepConfirmationCountrySelector.global.scss");
const hooks_1 = require("../../../hooks/index.js");
const classnames_1 = __importDefault(require("classnames"));
const AutoFocusOnSelect_1 = require("hooks/AutoFocusOnSelect");
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const Translation_1 = require("translations/Translation");
const Icon_1 = __importStar(require("../../generic/Icon/Icon"));
const CountryCodesAndNumbers_1 = require("../../../models/CountryCodesAndNumbers");
const Select_1 = require("../../generic/Select/Select");
const StepConfirmationCountrySelector = (0, react_1.forwardRef)(function InnerStepConfirmationCountrySelector(props, ref) {
    const inputRef = (0, react_1.useRef)(null);
    (0, react_1.useImperativeHandle)(ref, () => inputRef.current);
    const { onDropdownClosed, onItemSelected, onTriggerClicked, isDropdownOpen, isFocused } = (0, AutoFocusOnSelect_1.useAutoFocusOnSelect)({
        ref: inputRef.current,
        focusOnSelected: false,
        disableOpenOnFocus: props.disableOpenOnFocus,
    });
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const { validationStatus, name, onChange, value = '' } = props;
    const [inputValue, setInputValue] = (0, react_1.useState)(value);
    (0, react_1.useEffect)(() => {
        setInputValue(value);
    }, [value]);
    const mergeCountries = () => {
        var _a;
        if (!((_a = hotel === null || hotel === void 0 ? void 0 : hotel.availableCountries) === null || _a === void 0 ? void 0 : _a.length)) {
            return CountryCodesAndNumbers_1.ListOfCountriesAndCodes;
        }
        return hotel.availableCountries
            .filter(({ name }) => {
            return CountryCodesAndNumbers_1.ListOfCountriesAndCodes.some(({ label, otherLabels }) => label.toLowerCase() === name.toLowerCase() || (otherLabels && otherLabels.map((label) => label.toLowerCase()).includes(name.toLowerCase())));
        })
            .map(({ name, value }) => {
            const existedCountry = CountryCodesAndNumbers_1.ListOfCountriesAndCodes.find(({ label, otherLabels }) => label.toLowerCase() === name.toLowerCase() || (otherLabels && otherLabels.map((label) => label.toLowerCase()).includes(name.toLowerCase())));
            return Object.assign(Object.assign({}, existedCountry), { label: name, id: parseInt(value) });
        });
    };
    const organizedCountries = (0, react_1.useMemo)(() => {
        return mergeCountries().sort((a, b) => {
            return `${(a.suggested ? '000' : '') + a.label}`.localeCompare(`${(b.suggested ? '000' : '') + b.label}`);
        });
    }, [CountryCodesAndNumbers_1.ListOfCountriesAndCodes, hotel === null || hotel === void 0 ? void 0 : hotel.availableCountries]);
    const filterCountries = (0, react_1.useCallback)((inputValue) => {
        return organizedCountries.filter(({ label }) => label.toUpperCase().includes(inputValue.toUpperCase()));
    }, [organizedCountries]);
    const [options, setOptions] = (0, react_1.useState)(filterCountries(value));
    const { t } = (0, react_i18next_1.useTranslation)();
    const container = (0, react_1.useRef)(null);
    const emptyValue = () => {
        onChange === null || onChange === void 0 ? void 0 : onChange({ target: { name, value: '' } });
        setInputValue('');
        setOptions(organizedCountries);
    };
    const onInputChanged = (e) => {
        var _a;
        const value = ((_a = e.target.value) === null || _a === void 0 ? void 0 : _a.trim()) || '';
        if (value) {
            const options = filterCountries(value);
            setOptions(options);
            const exactCountry = options.find(({ label }) => label === value);
            if (exactCountry) {
                onCountryClick(exactCountry);
            }
        }
        else {
            setOptions(organizedCountries);
        }
        setInputValue(e.target.value);
    };
    const fieldClasses = (0, classnames_1.default)('rs-enhanced-country-field', {
        [`--${validationStatus}`]: !!validationStatus,
        '--focused': isFocused,
        '--disabled': props.disabled,
    });
    const onCountryClick = (country) => {
        var _a, _b;
        setInputValue(country.label);
        onItemSelected();
        onChange === null || onChange === void 0 ? void 0 : onChange({ target: { name, value: country.label } });
        if (country['id']) {
            (_a = props.onChangeId) === null || _a === void 0 ? void 0 : _a.call(props, country.id);
        }
        if (country['code']) {
            (_b = props.onChangeCode) === null || _b === void 0 ? void 0 : _b.call(props, country.code);
        }
    };
    const getOption = (key) => {
        return options.find(({ label }) => label === key);
    };
    const onClose = (e) => {
        onDropdownClosed(e);
        if (organizedCountries.every(({ label }) => { var _a; return label !== ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.value); })) {
            emptyValue();
        }
    };
    return (react_1.default.createElement("div", { className: fieldClasses },
        react_1.default.createElement("div", { className: "rs-enhanced-country-field--anchor", ref: container }),
        react_1.default.createElement("div", { className: "rs-enhanced-country-field--search" },
            react_1.default.createElement("input", { disabled: props.disabled, ref: inputRef, placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.Country) + (props.required ? ' *' : ''), onChange: onInputChanged, value: inputValue }),
            react_1.default.createElement("div", { onClick: () => {
                    var _a;
                    emptyValue();
                    (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
                }, className: (0, classnames_1.default)('rs-enhanced-country-field--close', {
                    '--hide': !inputValue,
                }) },
                react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.Close })),
            react_1.default.createElement("div", { className: "rs-enhanced-country-field--country", onClick: onTriggerClicked },
                react_1.default.createElement(Icon_1.default, { icon: Icon_1.IconType.Dropdown }))),
        react_1.default.createElement(Select_1.Select, { offset: [0, 21], open: isDropdownOpen, onClose: onClose, target: container.current, options: options, value: value, onChange: (value) => {
                const option = getOption(value);
                if (option) {
                    onCountryClick(option);
                }
            }, keyName: "label", renderOption: (country) => (react_1.default.createElement("div", { className: "rs-enhanced-country-field--suggest-list-country" },
                react_1.default.createElement("div", { className: "rs-enhanced-country-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-country-field--suggest-list-country-name" }, country === null || country === void 0 ? void 0 :
                    country.label,
                    " (", country === null || country === void 0 ? void 0 :
                    country.code,
                    ")"))) })));
});
exports.default = StepConfirmationCountrySelector;
//# sourceMappingURL=StepConfirmationCountrySelector.js.map