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, { useCallback, useRef, useMemo, useState, useEffect } from 'react';
import { identity, isEmpty, nthArg, path, pipe, prop, remove, T, uniq, isNil } from 'ramda';
import classnames from 'classnames';
import { debounce, isEmptyValue, wrapInArrayIfNeeded } from '@reltio/mdm-sdk';
import Autosuggest from 'react-autosuggest';
import { AutosizeInput } from '../AutosizeInput';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import Paper from '@mui/material/Paper';
import { useSafePromise } from '../hooks/useSafePromise';
import { useDidUpdateEffect } from '../hooks/useDidUpdateEffect';
import { Popper } from '../Popper';
import { EmptySearchResult } from '../EmptySearchResult';
import { ExpandedValueTooltip } from '../ExpandedValueTooltip';
import { ValueChip } from '../ValueChip';
import { ReactSelectLoadMoreButton } from '../ReactSelectLoadMoreButton';
import { useStyles } from './styles';
var FETCH_DEBOUNCE_INTERVAL = 300;
var PAGE_SIZE = 50;
var ChangeMethod;
(function (ChangeMethod) {
    ChangeMethod["Type"] = "type";
    ChangeMethod["Escape"] = "escape";
    ChangeMethod["Click"] = "click";
    ChangeMethod["Enter"] = "enter";
})(ChangeMethod || (ChangeMethod = {}));
export var TypeaheadEditor = function (_a) {
    var valueProp = _a.value, _b = _a.max, max = _b === void 0 ? PAGE_SIZE : _b, getSuggestions = _a.getSuggestions, onChange = _a.onChange, multiple = _a.multiple, fullWidth = _a.fullWidth, _c = _a.InputProps, InputProps = _c === void 0 ? {} : _c, _d = _a.isCrossedOut, isCrossedOut = _d === void 0 ? false : _d, inputProps = __rest(_a, ["value", "max", "getSuggestions", "onChange", "multiple", "fullWidth", "InputProps", "isCrossedOut"]);
    var styles = useStyles();
    var inputRef = useRef(null);
    var safePromise = useSafePromise();
    var _e = useState([]), suggestions = _e[0], setSuggestions = _e[1];
    var _f = useState(false), isPlaceholderVisible = _f[0], setPlaceholderVisibility = _f[1];
    var _g = useState(1), pageNumber = _g[0], setPageNumber = _g[1];
    var _h = useState(false), nextPageIsLoading = _h[0], setNextPageIsLoading = _h[1];
    var _j = useState(''), inputValue = _j[0], setInputValue = _j[1];
    var _k = useState(null), highlightedItem = _k[0], setHighlightedItem = _k[1];
    var pageSizeForRequest = max + 1;
    var displayedSuggestions = useMemo(function () { return suggestions.slice(0, pageNumber * max); }, [suggestions, pageNumber, max]);
    var showMoreButton = suggestions.length > displayedSuggestions.length;
    var value = multiple === true && !isNil(valueProp) ? wrapInArrayIfNeeded(valueProp) : valueProp;
    var isFocused = function () { var _a; return ((_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('input')) === document.activeElement; };
    var fetchSuggestions = useCallback(function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
        var response, error_1;
        var value = _b.value;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    response = [];
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, safePromise(getSuggestions(value.trim(), pageSizeForRequest))];
                case 2:
                    response = _c.sent();
                    return [3 /*break*/, 4];
                case 3:
                    error_1 = _c.sent();
                    console.warn(error_1);
                    return [3 /*break*/, 4];
                case 4:
                    setSuggestions(response);
                    setPlaceholderVisibility(isEmpty(response) && isFocused());
                    return [2 /*return*/];
            }
        });
    }); }, [safePromise, getSuggestions, pageSizeForRequest]);
    var debouncedFetchSuggestions = useCallback(debounce(fetchSuggestions, FETCH_DEBOUNCE_INTERVAL), [
        getSuggestions
    ]);
    var handleLoadMoreSuggestions = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
        var response_1, error_2;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setNextPageIsLoading(true);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, 4, 5]);
                    return [4 /*yield*/, getSuggestions(inputValue, pageSizeForRequest, pageNumber + 1)];
                case 2:
                    response_1 = _a.sent();
                    setSuggestions(function (prevSuggestions) { return __spreadArray(__spreadArray([], prevSuggestions, true), response_1, true); });
                    setPageNumber(function (prevPageNumber) { return prevPageNumber + 1; });
                    return [3 /*break*/, 5];
                case 3:
                    error_2 = _a.sent();
                    console.warn(error_2);
                    return [3 /*break*/, 5];
                case 4:
                    setNextPageIsLoading(false);
                    return [7 /*endfinally*/];
                case 5: return [2 /*return*/];
            }
        });
    }); }, [getSuggestions, inputValue, pageNumber, pageSizeForRequest]);
    var handleSuggestionsFetchRequested = useCallback(function (value) {
        if (value.reason === 'input-changed') {
            debouncedFetchSuggestions(value);
        }
        else {
            fetchSuggestions(value);
        }
    }, [debouncedFetchSuggestions, fetchSuggestions]);
    var handleSuggestionsClearRequested = useCallback(function () {
        setSuggestions([]);
        setPlaceholderVisibility(false);
        setPageNumber(1);
    }, []);
    var handleSuggestionHighlighted = useCallback(function (_a) {
        var suggestion = _a.suggestion;
        setHighlightedItem(suggestion);
    }, []);
    var handleInputValueChange = useCallback(function (_a) {
        var newValue = _a.newValue, method = _a.method;
        switch (method) {
            case ChangeMethod.Type:
            case ChangeMethod.Escape:
                setInputValue(newValue);
                break;
            case ChangeMethod.Click:
            case ChangeMethod.Enter: {
                if (multiple === true) {
                    if (newValue)
                        onChange(uniq(__spreadArray(__spreadArray([], (value || []), true), [newValue], false)));
                    setInputValue('');
                }
                else {
                    setInputValue(newValue);
                }
            }
        }
    }, [multiple, onChange, value]);
    var handleKeyDown = useCallback(function (event) {
        if (event.key !== 'Enter' || highlightedItem)
            return;
        if (multiple === true) {
            handleInputValueChange({ method: ChangeMethod.Enter, newValue: inputValue });
        }
        else {
            onChange(inputValue);
        }
    }, [handleInputValueChange, onChange, highlightedItem, inputValue, multiple]);
    var handleBlur = useCallback(function () {
        if (multiple !== true) {
            onChange(inputValue);
        }
        else {
            handleInputValueChange({ method: ChangeMethod.Enter, newValue: inputValue });
        }
    }, [inputValue, onChange, multiple, handleInputValueChange]);
    useEffect(function () {
        var _a;
        if (multiple !== true)
            setInputValue((_a = value) !== null && _a !== void 0 ? _a : '');
    }, [value, multiple]);
    useDidUpdateEffect(function () {
        setPageNumber(1);
    }, [inputValue]);
    return (React.createElement(Autosuggest, { key: multiple, suggestions: displayedSuggestions, shouldRenderSuggestions: T, getSuggestionValue: identity, onSuggestionsFetchRequested: handleSuggestionsFetchRequested, onSuggestionsClearRequested: handleSuggestionsClearRequested, onSuggestionHighlighted: handleSuggestionHighlighted, theme: {
            container: fullWidth ? styles.suggestionsContainer : '',
            suggestionsList: styles.suggestionsList,
            suggestionsContainerOpen: styles.suggestionsContainerOpen
        }, inputProps: __assign({ value: inputValue, onChange: pipe(nthArg(1), handleInputValueChange), onKeyDown: handleKeyDown, onBlur: handleBlur, fullWidth: fullWidth, variant: 'standard', autoComplete: 'off' }, inputProps), renderInputComponent: function (_a) {
            var _b, _c;
            var ref = _a.ref, otherProps = __rest(_a, ["ref"]);
            var commonClasses = {
                underline: classnames((_b = {}, _b[styles.underline] = isEmptyValue(value), _b)),
                input: classnames(styles['rawInput'], path(['classes', 'input'], InputProps))
            };
            return multiple === true ? (React.createElement(TextField, __assign({}, otherProps, { ref: inputRef, inputRef: ref, InputProps: __assign(__assign({}, InputProps), { startAdornment: value === null || value === void 0 ? void 0 : value.map(function (item, index) { return (React.createElement(ValueChip, { key: item, label: item, onDelete: function () { return onChange(remove(index, 1, value)); } })); }), inputComponent: AutosizeInput, classes: __assign(__assign({ root: classnames(styles.multipleTextFieldInput, path(['classes', 'root'], InputProps)) }, commonClasses), { input: classnames(styles.autosizeInput, commonClasses.input), adornedStart: styles.multipleTextFieldAdornedStart }) }), classes: { root: styles.multipleTextField } }))) : (React.createElement(TextField, __assign({}, otherProps, { ref: inputRef, inputRef: ref, InputProps: __assign(__assign({}, InputProps), { classes: __assign({ root: classnames(styles.inputRoot, path(['classes', 'root'], InputProps), (_c = {},
                            _c[styles.isCrossedOut] = isCrossedOut,
                            _c)) }, commonClasses) }) })));
        }, renderSuggestionsContainer: function (_a) {
            var children = _a.children, _b = _a.containerProps, ref = _b.ref, restContainerProps = __rest(_b, ["ref"]);
            return (React.createElement(Popper, { anchorEl: inputRef.current, open: Boolean(children) || isPlaceholderVisible },
                React.createElement(Paper, __assign({}, restContainerProps, { ref: ref, square: true, style: { width: prop('clientWidth', inputRef.current) } }),
                    children || React.createElement(EmptySearchResult, { className: styles.suggestionsPlaceholder }),
                    showMoreButton && !isPlaceholderVisible && (React.createElement(ReactSelectLoadMoreButton, { onClick: handleLoadMoreSuggestions, onMouseDown: function (event) { return event.preventDefault(); }, loading: nextPageIsLoading })))));
        }, renderSuggestion: function (suggestion, _a) {
            var isHighlighted = _a.isHighlighted;
            return (React.createElement(MenuItem, { className: styles.suggestionsItem, selected: isHighlighted, component: "div" },
                React.createElement(ExpandedValueTooltip, { value: suggestion },
                    React.createElement("div", { className: styles.suggestionsItemText }, suggestion))));
        } }));
};
