"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddressAutocompleteEditor = exports.INPUT_DEBOUNCE_INTERVAL = void 0;
var react_1 = __importStar(require("react"));
var classnames_1 = __importDefault(require("classnames"));
var ramda_1 = require("ramda");
var react_context_selector_1 = require("@fluentui/react-context-selector");
var Autocomplete_1 = __importDefault(require("@mui/material/Autocomplete"));
var Button_1 = __importDefault(require("@mui/material/Button"));
var ChevronRight_1 = __importDefault(require("@mui/icons-material/ChevronRight"));
var LinearProgress_1 = __importDefault(require("@mui/material/LinearProgress"));
var ListItemButton_1 = __importDefault(require("@mui/material/ListItemButton"));
var TextField_1 = __importDefault(require("@mui/material/TextField"));
var Typography_1 = __importDefault(require("@mui/material/Typography"));
var ui_i18n_1 = __importDefault(require("ui-i18n"));
var mdm_sdk_1 = require("@reltio/mdm-sdk");
var AutoCompleteContext_1 = require("../contexts/AutoCompleteContext");
var AttributeValueContext_1 = require("../contexts/AttributeValueContext");
var helpers_1 = require("./helpers");
var useSafePromise_1 = require("../hooks/useSafePromise");
var ExpandedValueTooltip_1 = require("../ExpandedValueTooltip");
var EmptySearchResult_1 = require("../EmptySearchResult");
var AddressAutocompleteEditor_module_css_1 = __importDefault(require("./AddressAutocompleteEditor.module.css"));
exports.INPUT_DEBOUNCE_INTERVAL = 400;
var EMPTY_OPTION_ID = 'empty_option_id';
var AddressAutocompleteEditor = function (_a) {
    var _b = _a.value, value = _b === void 0 ? '' : _b, onChange = _a.onChange, InputProps = _a.InputProps, _c = _a.fullWidth, fullWidth = _c === void 0 ? true : _c, otherProps = __rest(_a, ["value", "onChange", "InputProps", "fullWidth"]);
    var _d = (0, react_1.useState)(value), inputValue = _d[0], setInputValue = _d[1];
    var _e = (0, react_1.useState)(null), options = _e[0], setOptions = _e[1];
    var _f = (0, react_1.useState)([]), previousOptions = _f[0], setPreviousOptions = _f[1];
    var _g = (0, react_1.useState)(false), loading = _g[0], setLoading = _g[1];
    var _h = (0, react_1.useState)(false), open = _h[0], setOpen = _h[1];
    var searchSafePromise = (0, useSafePromise_1.useSafePromise)();
    var detailsSafePromise = (0, useSafePromise_1.useSafePromise)();
    var onPopulateAttributes = (0, react_context_selector_1.useContextSelector)(AutoCompleteContext_1.AddressAutoCompleteContext, function (c) { return c === null || c === void 0 ? void 0 : c.onPopulateAttributes; });
    var getAutocompleteSettings = (0, react_context_selector_1.useContextSelector)(AutoCompleteContext_1.AddressAutoCompleteContext, function (c) { return c === null || c === void 0 ? void 0 : c.getAutocompleteSettings; });
    var _j = (0, react_1.useContext)(AttributeValueContext_1.AttributeValueContext) || {}, valueUri = _j.uri, attributeTypeUri = _j.type;
    var autocompleteSettings = (0, react_1.useMemo)(function () { return getAutocompleteSettings === null || getAutocompleteSettings === void 0 ? void 0 : getAutocompleteSettings(attributeTypeUri, valueUri); }, [getAutocompleteSettings, valueUri, attributeTypeUri]);
    var countries = autocompleteSettings.countries, countryNames = autocompleteSettings.countryNames, limit = autocompleteSettings.limit, minSearchTextLen = autocompleteSettings.minSearchTextLen;
    var countriesHash = countries.toString();
    (0, react_1.useEffect)(function () {
        setOptions(null);
        setPreviousOptions([]);
    }, [countriesHash]);
    var fetchAddressSuggestions = (0, react_1.useCallback)(function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
        var results, _c, convertedOptions, error_1;
        var searchTerm = _b.searchTerm, container = _b.container;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    setLoading(true);
                    _d.label = 1;
                case 1:
                    _d.trys.push([1, 6, 7, 8]);
                    if (!container) return [3 /*break*/, 3];
                    return [4 /*yield*/, searchSafePromise((0, mdm_sdk_1.searchAddresses)({ container: container }))];
                case 2:
                    _c = _d.sent();
                    return [3 /*break*/, 5];
                case 3: return [4 /*yield*/, searchSafePromise((0, mdm_sdk_1.searchAddresses)({
                        text: searchTerm,
                        limit: limit,
                        countries: countries
                    }))];
                case 4:
                    _c = _d.sent();
                    _d.label = 5;
                case 5:
                    results = _c;
                    convertedOptions = results.map(helpers_1.convertSearchResultToOption);
                    if (container) {
                        setPreviousOptions(options || []);
                    }
                    else {
                        setPreviousOptions([]);
                    }
                    setOptions(convertedOptions);
                    return [3 /*break*/, 8];
                case 6:
                    error_1 = _d.sent();
                    console.warn('Error fetching address suggestions:', error_1);
                    setOptions([]);
                    return [3 /*break*/, 8];
                case 7:
                    setLoading(false);
                    return [7 /*endfinally*/];
                case 8: return [2 /*return*/];
            }
        });
    }); }, [countries, limit, searchSafePromise, options]);
    var fetchAddressDetailsById = (0, react_1.useCallback)(function (addressId) { return __awaiter(void 0, void 0, void 0, function () {
        var error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setLoading(true);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, 4, 5]);
                    return [4 /*yield*/, detailsSafePromise((0, mdm_sdk_1.fetchAddressDetails)(addressId))];
                case 2: return [2 /*return*/, _a.sent()];
                case 3:
                    error_2 = _a.sent();
                    console.warn('Error fetching address details:', error_2);
                    return [3 /*break*/, 5];
                case 4:
                    setLoading(false);
                    return [7 /*endfinally*/];
                case 5: return [2 /*return*/];
            }
        });
    }); }, [detailsSafePromise]);
    var debouncedFetchAddressSuggestions = (0, react_1.useCallback)((0, mdm_sdk_1.debounce)(fetchAddressSuggestions, exports.INPUT_DEBOUNCE_INTERVAL), [
        fetchAddressSuggestions
    ]);
    var handleInputChange = (0, react_1.useCallback)(function (event, newInputValue, reason) {
        if (reason === 'reset') {
            return;
        }
        setInputValue(newInputValue);
        if ((0, helpers_1.isMinLength)(newInputValue, minSearchTextLen)) {
            debouncedFetchAddressSuggestions({ searchTerm: newInputValue });
        }
        else {
            setOptions([]);
            setPreviousOptions([]);
        }
    }, [debouncedFetchAddressSuggestions, minSearchTextLen]);
    var handleOptionSelect = (0, react_1.useCallback)(function (event, selectedOption) { return __awaiter(void 0, void 0, void 0, function () {
        var addressDetail;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!selectedOption) return [3 /*break*/, 3];
                    if (selectedOption.type === mdm_sdk_1.AddressType.Container) {
                        fetchAddressSuggestions({ container: selectedOption.id });
                        return [2 /*return*/];
                    }
                    setInputValue(selectedOption.fullAddress);
                    setPreviousOptions([]);
                    if (onChange) {
                        onChange(selectedOption.fullAddress);
                    }
                    if (!onPopulateAttributes) return [3 /*break*/, 2];
                    return [4 /*yield*/, fetchAddressDetailsById(selectedOption.id)];
                case 1:
                    addressDetail = _a.sent();
                    onPopulateAttributes(attributeTypeUri, valueUri, addressDetail === null || addressDetail === void 0 ? void 0 : addressDetail[0]);
                    _a.label = 2;
                case 2:
                    setOpen(false);
                    return [3 /*break*/, 4];
                case 3:
                    setInputValue('');
                    if (onChange) {
                        onChange('');
                    }
                    _a.label = 4;
                case 4: return [2 /*return*/];
            }
        });
    }); }, [fetchAddressDetailsById, fetchAddressSuggestions, onChange, onPopulateAttributes, attributeTypeUri, valueUri]);
    var handleFocus = (0, react_1.useCallback)(function () {
        if (!options && (0, helpers_1.isMinLength)(inputValue, minSearchTextLen)) {
            debouncedFetchAddressSuggestions({ searchTerm: inputValue });
        }
        setOpen(true);
    }, [debouncedFetchAddressSuggestions, inputValue, minSearchTextLen, options]);
    var handleBlur = (0, react_1.useCallback)(function () {
        setOpen(false);
    }, []);
    var renderOption = (0, react_1.useCallback)(function (props, option) {
        if (option.id === EMPTY_OPTION_ID) {
            return null;
        }
        var isContainer = option.type === mdm_sdk_1.AddressType.Container;
        return (react_1.default.createElement(ListItemButton_1.default, __assign({}, props, { className: (0, classnames_1.default)(props.className, AddressAutocompleteEditor_module_css_1.default.option), component: "li", disabled: loading }),
            react_1.default.createElement("div", { className: AddressAutocompleteEditor_module_css_1.default.optionTextWrapper },
                react_1.default.createElement(ExpandedValueTooltip_1.ExpandedValueTooltip, { value: option.fullAddress },
                    react_1.default.createElement(Typography_1.default, { variant: "body2", component: "span", className: AddressAutocompleteEditor_module_css_1.default.optionText }, option.fullAddress)),
                option.description && isContainer && (react_1.default.createElement(ExpandedValueTooltip_1.ExpandedValueTooltip, { value: option.description },
                    react_1.default.createElement(Typography_1.default, { variant: "caption", component: "span", className: AddressAutocompleteEditor_module_css_1.default.description }, option.description)))),
            isContainer && (react_1.default.createElement("div", { className: AddressAutocompleteEditor_module_css_1.default.containerForwardIcon },
                react_1.default.createElement(ChevronRight_1.default, null)))));
    }, [loading]);
    var renderInput = (0, react_1.useCallback)(function (props) {
        var _a;
        return (react_1.default.createElement(TextField_1.default, __assign({}, props, otherProps, { placeholder: ui_i18n_1.default.text('Start typing to autocomplete'), fullWidth: fullWidth, onBlur: handleBlur, InputProps: __assign(__assign(__assign({}, props.InputProps), InputProps), { classes: __assign(__assign({}, InputProps === null || InputProps === void 0 ? void 0 : InputProps.classes), { root: (0, classnames_1.default)(AddressAutocompleteEditor_module_css_1.default.textFieldRoot, (0, ramda_1.path)(['classes', 'root'], InputProps)), input: (0, classnames_1.default)(AddressAutocompleteEditor_module_css_1.default.textFieldInput, (0, ramda_1.path)(['classes', 'input'], InputProps)), underline: (0, classnames_1.default)((_a = {}, _a[AddressAutocompleteEditor_module_css_1.default.underline] = (0, mdm_sdk_1.isEmptyValue)(value), _a)) }) }) })));
    }, [fullWidth, handleBlur, InputProps, otherProps, value]);
    var handleBackToAllSearchResults = (0, react_1.useCallback)(function () {
        setOptions(previousOptions);
        setPreviousOptions([]);
    }, [previousOptions]);
    var renderListbox = (0, react_1.useCallback)(react_1.default.forwardRef(function ListboxComponent(props, ref) {
        var onMouseDown = props.onMouseDown, restProps = __rest(props, ["onMouseDown"]);
        var shouldShowEmptyState = (options === null || options === void 0 ? void 0 : options.length) === 0 && (0, helpers_1.isMinLength)(inputValue, minSearchTextLen) && !loading;
        var shouldShowMinLengthMessage = !(0, helpers_1.isMinLength)(inputValue, minSearchTextLen) && !loading;
        var shouldShowOptions = (options === null || options === void 0 ? void 0 : options.length) > 0 && !shouldShowMinLengthMessage;
        var countriesLabel = countryNames.join(', ');
        return (react_1.default.createElement("div", { onMouseDown: onMouseDown },
            loading && react_1.default.createElement(LinearProgress_1.default, { className: AddressAutocompleteEditor_module_css_1.default.loadingProgress, color: "primary" }),
            react_1.default.createElement("div", { className: AddressAutocompleteEditor_module_css_1.default.countryHeader },
                react_1.default.createElement(ExpandedValueTooltip_1.ExpandedValueTooltip, { value: countriesLabel },
                    react_1.default.createElement(Typography_1.default, { variant: "body2", color: "textSecondary", className: AddressAutocompleteEditor_module_css_1.default.headerCountries },
                        ui_i18n_1.default.text('Searching in'),
                        ": ",
                        countriesLabel)),
                react_1.default.createElement(Typography_1.default, { variant: "caption", color: "textSecondary", className: AddressAutocompleteEditor_module_css_1.default.headerHelper }, ui_i18n_1.default.text('To search in a different country, update the Country field'))),
            react_1.default.createElement("ul", __assign({ ref: ref }, restProps, { className: AddressAutocompleteEditor_module_css_1.default.listbox }),
                shouldShowMinLengthMessage && (react_1.default.createElement("li", { className: AddressAutocompleteEditor_module_css_1.default.emptyState },
                    react_1.default.createElement(Typography_1.default, { variant: "body2", color: "textSecondary" }, ui_i18n_1.default.text('Please enter at least ${minSearchTextLen} characters', {
                        minSearchTextLen: minSearchTextLen
                    })))),
                shouldShowEmptyState && (react_1.default.createElement("li", { className: AddressAutocompleteEditor_module_css_1.default.emptyState },
                    react_1.default.createElement(EmptySearchResult_1.EmptySearchResult, { className: AddressAutocompleteEditor_module_css_1.default.noData }))),
                shouldShowOptions && props.children),
            previousOptions.length > 0 && (react_1.default.createElement("div", { className: AddressAutocompleteEditor_module_css_1.default.backToAllResults },
                react_1.default.createElement(Button_1.default, { variant: "text", onClick: handleBackToAllSearchResults, color: "primary", disabled: loading, classes: { root: AddressAutocompleteEditor_module_css_1.default.backToAllResultsButton } }, ui_i18n_1.default.text('Back to all results'))))));
    }), [loading, countryNames, previousOptions.length, (options || []).length, inputValue, minSearchTextLen]);
    var openOptionsList = (0, react_1.useCallback)(function (_event) {
        setOpen(true);
    }, []);
    var displayOptions = (0, react_1.useMemo)(function () {
        return __spreadArray([{ id: EMPTY_OPTION_ID, type: mdm_sdk_1.AddressType.Address, fullAddress: '' }], (options || []), true);
    }, [options]);
    return (react_1.default.createElement(Autocomplete_1.default, { className: AddressAutocompleteEditor_module_css_1.default.root, open: open, onOpen: openOptionsList, value: inputValue, onChange: handleOptionSelect, inputValue: inputValue, onInputChange: handleInputChange, onFocus: handleFocus, options: displayOptions, getOptionLabel: helpers_1.getOptionLabel, renderInput: renderInput, renderOption: renderOption, renderGroup: function (params) { return params.children; }, ListboxComponent: renderListbox, classes: {
            paper: AddressAutocompleteEditor_module_css_1.default.popupContainer
        }, filterOptions: ramda_1.identity, isOptionEqualToValue: helpers_1.isOptionEqualToValue, popupIcon: null, clearIcon: null, freeSolo: true, "data-reltio-id": "address-autocomplete-editor" }));
};
exports.AddressAutocompleteEditor = AddressAutocompleteEditor;
