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 __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));
};
import React, { useState, useCallback, useMemo, useContext, useEffect } from 'react';
import classnames from 'classnames';
import { identity, path } from 'ramda';
import { useContextSelector } from '@fluentui/react-context-selector';
import Autocomplete from '@mui/material/Autocomplete';
import Button from '@mui/material/Button';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import LinearProgress from '@mui/material/LinearProgress';
import ListItemButton from '@mui/material/ListItemButton';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import i18n from 'ui-i18n';
import { searchAddresses, fetchAddressDetails, debounce, AddressType, isEmptyValue } from '@reltio/mdm-sdk';
import { AddressAutoCompleteContext } from '../contexts/AutoCompleteContext';
import { AttributeValueContext } from '../contexts/AttributeValueContext';
import { convertSearchResultToOption, getOptionLabel, isMinLength, isOptionEqualToValue } from './helpers';
import { useSafePromise } from '../hooks/useSafePromise';
import { ExpandedValueTooltip } from '../ExpandedValueTooltip';
import { EmptySearchResult } from '../EmptySearchResult';
import styles from './AddressAutocompleteEditor.module.css';
export var INPUT_DEBOUNCE_INTERVAL = 400;
var EMPTY_OPTION_ID = 'empty_option_id';
export 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 = useState(value), inputValue = _d[0], setInputValue = _d[1];
    var _e = useState(null), options = _e[0], setOptions = _e[1];
    var _f = useState([]), previousOptions = _f[0], setPreviousOptions = _f[1];
    var _g = useState(false), loading = _g[0], setLoading = _g[1];
    var _h = useState(false), open = _h[0], setOpen = _h[1];
    var searchSafePromise = useSafePromise();
    var detailsSafePromise = useSafePromise();
    var onPopulateAttributes = useContextSelector(AddressAutoCompleteContext, function (c) { return c === null || c === void 0 ? void 0 : c.onPopulateAttributes; });
    var getAutocompleteSettings = useContextSelector(AddressAutoCompleteContext, function (c) { return c === null || c === void 0 ? void 0 : c.getAutocompleteSettings; });
    var _j = useContext(AttributeValueContext) || {}, valueUri = _j.uri, attributeTypeUri = _j.type;
    var autocompleteSettings = 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();
    useEffect(function () {
        setOptions(null);
        setPreviousOptions([]);
    }, [countriesHash]);
    var fetchAddressSuggestions = 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(searchAddresses({ container: container }))];
                case 2:
                    _c = _d.sent();
                    return [3 /*break*/, 5];
                case 3: return [4 /*yield*/, searchSafePromise(searchAddresses({
                        text: searchTerm,
                        limit: limit,
                        countries: countries
                    }))];
                case 4:
                    _c = _d.sent();
                    _d.label = 5;
                case 5:
                    results = _c;
                    convertedOptions = results.map(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 = 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(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 = useCallback(debounce(fetchAddressSuggestions, INPUT_DEBOUNCE_INTERVAL), [
        fetchAddressSuggestions
    ]);
    var handleInputChange = useCallback(function (event, newInputValue, reason) {
        if (reason === 'reset') {
            return;
        }
        setInputValue(newInputValue);
        if (isMinLength(newInputValue, minSearchTextLen)) {
            debouncedFetchAddressSuggestions({ searchTerm: newInputValue });
        }
        else {
            setOptions([]);
            setPreviousOptions([]);
        }
    }, [debouncedFetchAddressSuggestions, minSearchTextLen]);
    var handleOptionSelect = 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 === 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 = useCallback(function () {
        if (!options && isMinLength(inputValue, minSearchTextLen)) {
            debouncedFetchAddressSuggestions({ searchTerm: inputValue });
        }
        setOpen(true);
    }, [debouncedFetchAddressSuggestions, inputValue, minSearchTextLen, options]);
    var handleBlur = useCallback(function () {
        setOpen(false);
    }, []);
    var renderOption = useCallback(function (props, option) {
        if (option.id === EMPTY_OPTION_ID) {
            return null;
        }
        var isContainer = option.type === AddressType.Container;
        return (React.createElement(ListItemButton, __assign({}, props, { className: classnames(props.className, styles.option), component: "li", disabled: loading }),
            React.createElement("div", { className: styles.optionTextWrapper },
                React.createElement(ExpandedValueTooltip, { value: option.fullAddress },
                    React.createElement(Typography, { variant: "body2", component: "span", className: styles.optionText }, option.fullAddress)),
                option.description && isContainer && (React.createElement(ExpandedValueTooltip, { value: option.description },
                    React.createElement(Typography, { variant: "caption", component: "span", className: styles.description }, option.description)))),
            isContainer && (React.createElement("div", { className: styles.containerForwardIcon },
                React.createElement(ChevronRightIcon, null)))));
    }, [loading]);
    var renderInput = useCallback(function (props) {
        var _a;
        return (React.createElement(TextField, __assign({}, props, otherProps, { placeholder: i18n.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: classnames(styles.textFieldRoot, path(['classes', 'root'], InputProps)), input: classnames(styles.textFieldInput, path(['classes', 'input'], InputProps)), underline: classnames((_a = {}, _a[styles.underline] = isEmptyValue(value), _a)) }) }) })));
    }, [fullWidth, handleBlur, InputProps, otherProps, value]);
    var handleBackToAllSearchResults = useCallback(function () {
        setOptions(previousOptions);
        setPreviousOptions([]);
    }, [previousOptions]);
    var renderListbox = useCallback(React.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 && isMinLength(inputValue, minSearchTextLen) && !loading;
        var shouldShowMinLengthMessage = !isMinLength(inputValue, minSearchTextLen) && !loading;
        var shouldShowOptions = (options === null || options === void 0 ? void 0 : options.length) > 0 && !shouldShowMinLengthMessage;
        var countriesLabel = countryNames.join(', ');
        return (React.createElement("div", { onMouseDown: onMouseDown },
            loading && React.createElement(LinearProgress, { className: styles.loadingProgress, color: "primary" }),
            React.createElement("div", { className: styles.countryHeader },
                React.createElement(ExpandedValueTooltip, { value: countriesLabel },
                    React.createElement(Typography, { variant: "body2", color: "textSecondary", className: styles.headerCountries },
                        i18n.text('Searching in'),
                        ": ",
                        countriesLabel)),
                React.createElement(Typography, { variant: "caption", color: "textSecondary", className: styles.headerHelper }, i18n.text('To search in a different country, update the Country field'))),
            React.createElement("ul", __assign({ ref: ref }, restProps, { className: styles.listbox }),
                shouldShowMinLengthMessage && (React.createElement("li", { className: styles.emptyState },
                    React.createElement(Typography, { variant: "body2", color: "textSecondary" }, i18n.text('Please enter at least ${minSearchTextLen} characters', {
                        minSearchTextLen: minSearchTextLen
                    })))),
                shouldShowEmptyState && (React.createElement("li", { className: styles.emptyState },
                    React.createElement(EmptySearchResult, { className: styles.noData }))),
                shouldShowOptions && props.children),
            previousOptions.length > 0 && (React.createElement("div", { className: styles.backToAllResults },
                React.createElement(Button, { variant: "text", onClick: handleBackToAllSearchResults, color: "primary", disabled: loading, classes: { root: styles.backToAllResultsButton } }, i18n.text('Back to all results'))))));
    }), [loading, countryNames, previousOptions.length, (options || []).length, inputValue, minSearchTextLen]);
    var openOptionsList = useCallback(function (_event) {
        setOpen(true);
    }, []);
    var displayOptions = useMemo(function () {
        return __spreadArray([{ id: EMPTY_OPTION_ID, type: AddressType.Address, fullAddress: '' }], (options || []), true);
    }, [options]);
    return (React.createElement(Autocomplete, { className: styles.root, open: open, onOpen: openOptionsList, value: inputValue, onChange: handleOptionSelect, inputValue: inputValue, onInputChange: handleInputChange, onFocus: handleFocus, options: displayOptions, getOptionLabel: getOptionLabel, renderInput: renderInput, renderOption: renderOption, renderGroup: function (params) { return params.children; }, ListboxComponent: renderListbox, classes: {
            paper: styles.popupContainer
        }, filterOptions: identity, isOptionEqualToValue: isOptionEqualToValue, popupIcon: null, clearIcon: null, freeSolo: true, "data-reltio-id": "address-autocomplete-editor" }));
};
