/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'jquery',
    'mage/template',
    'mage/mage',
    'jquery/ui',
    'mage/backend/menu',
    'mage/translate'
], function ($, mageTemplate) {
    'use strict';
    /**
     * Implement base functionality
     */
    $.widget('mage.suggest', {
        widgetEventPrefix: 'suggest',
        options: {
            template: '<% if (data.items.length) { %>' +
                '<% if (!data.term && !data.allShown() && data.recentShown()) { %>' +
                '
').text(JSON.stringify(item)).html().replace(/"/g, '"') + '"';
                },
                itemSelected: $.proxy(this._isItemSelected, this),
                noRecordsText: $.mage.__('No records found.')
            });
        },
        /**
         * @param {Object} item
         * @return {Boolean}
         * @private
         */
        _isItemSelected: function (item) {
            return item.id == (this._selectedItem && this._selectedItem.id ? //eslint-disable-line eqeqeq
                this._selectedItem.id :
                this.options.currentlySelected);
        },
        /**
         * Render content of suggest's dropdown
         * @param {Object} e - event object
         * @param {Array} items - list of label+id objects
         * @param {Object} context - template's context
         * @private
         */
        _renderDropdown: function (e, items, context) {
            var tmpl = this.templates[this.templateName];
            this._items = items;
            tmpl = tmpl({
                data: this._prepareDropdownContext(context)
            });
            $(tmpl).appendTo(this.dropdown.empty());
            this.dropdown.trigger('contentUpdated')
                .find(this._control.selector).on('focus', function (event) {
                    event.preventDefault();
                });
            this._renderedContext = context;
            this.element.removeClass(this.options.loadingClass);
            this.open(e);
        },
        /**
         * @param {Object} e
         * @param {Object} items
         * @param {Object} context
         * @private
         */
        _processResponse: function (e, items, context) {
            var renderer = $.proxy(function (i) {
                return this._renderDropdown(e, i, context || {});
            }, this);
            if (this._trigger('response', e, [items, renderer]) === false) {
                return;
            }
            this._renderDropdown(e, items, context);
        },
        /**
         * Implement search process via spesific source
         * @param {String} term - search phrase
         * @param {Function} response - search results handler, process search result
         * @private
         */
        _source: function (term, response) {
            var o = this.options,
                ajaxData;
            if (Array.isArray(o.source)) {
                response(this.filter(o.source, term));
            } else if (typeof o.source === 'string') {
                ajaxData = {};
                ajaxData[this.options.termAjaxArgument] = term;
                this._xhr = $.ajax($.extend(true, {
                    url: o.source,
                    type: 'POST',
                    dataType: 'json',
                    data: ajaxData,
                    success: $.proxy(function (items) {
                        this.options.data = items;
                        response.apply(response, arguments);
                    }, this)
                }, o.ajaxOptions || {}));
            } else if (typeof o.source === 'function') {
                o.source.apply(o.source, arguments);
            }
        },
        /**
         * Abort search process
         * @private
         */
        _abortSearch: function () {
            this.element.removeClass(this.options.loadingClass);
            clearTimeout(this._searchTimeout);
        },
        /**
         * Perform filtering in advance loaded items and returns search result
         * @param {Array} items - all available items
         * @param {String} term - search phrase
         * @return {Object}
         */
        filter: function (items, term) {
            var matcher = new RegExp(term.replace(/[\-\/\\\^$*+?.()|\[\]{}]/g, '\\$&'), 'i'),
                itemsArray = Array.isArray(items) ? items : $.map(items, function (element) {
                    return element;
                }),
                property = this.options.filterProperty;
            return $.grep(
                itemsArray,
                function (value) {
                    return matcher.test(value[property] || value.id || value);
                }
            );
        }
    });
    /**
     * Implement show all functionality and storing and display recent searches
     */
    $.widget('mage.suggest', $.mage.suggest, {
        options: {
            showRecent: false,
            showAll: false,
            storageKey: 'suggest',
            storageLimit: 10
        },
        /**
         * @override
         */
        _create: function () {
            var recentItems;
            if (this.options.showRecent && window.localStorage) {
                recentItems = JSON.parse(localStorage.getItem(this.options.storageKey));
                /**
                 * @type {Array} - list of recently searched items
                 * @private
                 */
                this._recentItems = Array.isArray(recentItems) ? recentItems : [];
            }
            this._super();
        },
        /**
         * @override
         */
        _bind: function () {
            this._super();
            this._on(this.dropdown, {
                /**
                 * @param {jQuery.Event} e
                 */
                showAll: function (e) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    this.element.trigger('showAll');
                }
            });
            if (this.options.showRecent || this.options.showAll) {
                this._on({
                    /**
                     * @param {jQuery.Event} e
                     */
                    focus: function (e) {
                        if (!this.isDropdownShown()) {
                            this.search(e);
                        }
                    },
                    showAll: this._showAll
                });
            }
        },
        /**
         * @private
         * @param {Object} e - event object
         */
        _showAll: function (e) {
            this._abortSearch();
            this._search(e, '', {
                _allShown: true
            });
        },
        /**
         * @override
         */
        search: function (e) {
            if (!this._value()) {
                if (this.options.showRecent) {
                    if (this._recentItems.length) { //eslint-disable-line max-depth
                        this._processResponse(e, this._recentItems, {});
                    } else {
                        this._showAll(e);
                    }
                } else if (this.options.showAll) {
                    this._showAll(e);
                }
            }
            this._superApply(arguments);
        },
        /**
         * @override
         */
        _selectItem: function () {
            this._superApply(arguments);
            if (this._selectedItem && this._selectedItem.id && this.options.showRecent) {
                this._addRecent(this._selectedItem);
            }
        },
        /**
         * @override
         */
        _prepareDropdownContext: function () {
            var context = this._superApply(arguments);
            return $.extend(context, {
                recentShown: $.proxy(function () {
                    return this.options.showRecent;
                }, this),
                recentTitle: $.mage.__('Recent items'),
                showAllTitle: $.mage.__('Show all...'),
                /**
                 * @return {Boolean}
                 */
                allShown: function () {
                    return !!context._allShown;
                }
            });
        },
        /**
         * Add selected item of search result into storage of recents
         * @param {Object} item - label+id object
         * @private
         */
        _addRecent: function (item) {
            this._recentItems = $.grep(this._recentItems, function (obj) {
                return obj.id !== item.id;
            });
            this._recentItems.unshift(item);
            this._recentItems = this._recentItems.slice(0, this.options.storageLimit);
            localStorage.setItem(this.options.storageKey, JSON.stringify(this._recentItems));
        }
    });
    /**
     * Implement multi suggest functionality
     */
    $.widget('mage.suggest', $.mage.suggest, {
        options: {
            multiSuggestWrapper: '
' +
                '- <' +
                'label class="mage-suggest-search-label">
 
',
            choiceTemplate: '
<%- text %>
' +
            '',
            selectedClass: 'mage-suggest-selected'
        },
        /**
         * @override
         */
        _create: function () {
            this.choiceTmpl = mageTemplate(this.options.choiceTemplate);
            this._super();
            if (this.options.multiselect) {
                this.valueField.hide();
            }
        },
        /**
         * @override
         */
        _render: function () {
            this._super();
            if (this.options.multiselect) {
                this._renderMultiselect();
            }
        },
        /**
         * Render selected options
         * @private
         */
        _renderMultiselect: function () {
            var that = this;
            this.element.wrap(this.options.multiSuggestWrapper);
            this.elementWrapper = this.element.closest('[data-role="parent-choice-element"]');
            $(function () {
                that._getOptions()
                    .each(function (i, option) {
                        option = $(option);
                        that._createOption({
                            id: option.val(),
                            label: option.text()
                        });
                    });
            });
        },
        /**
         * @return {Array} array of DOM-elements
         * @private
         */
        _getOptions: function () {
            return this.valueField.find('option');
        },
        /**
         * @override
         */
        _bind: function () {
            this._super();
            if (this.options.multiselect) {
                this._on({
                    /**
                     * @param {jQuery.Event} event
                     */
                    keydown: function (event) {
                        if (event.keyCode === $.ui.keyCode.BACKSPACE) {
                            if (!this._value()) {
                                this._removeLastAdded(event);
                            }
                        }
                    },
                    removeOption: this.removeOption
                });
            }
        },
        /**
         * @param {Array} items
         * @return {Array}
         * @private
         */
        _filterSelected: function (items) {
            var options = this._getOptions();
            return $.grep(items, function (value) {
                var itemSelected = false;
                $.each(options, function () {
                    if (value.id == $(this).val()) { //eslint-disable-line eqeqeq
                        itemSelected = true;
                    }
                });
                return !itemSelected;
            });
        },
        /**
         * @override
         */
        _processResponse: function (e, items, context) {
            if (this.options.multiselect) {
                items = this._filterSelected(items, context);
            }
            this._superApply([e, items, context]);
        },
        /**
         * @override
         */
        _prepareValueField: function () {
            this._super();
            if (this.options.multiselect && !this.options.valueField && this.options.selectedItems) {
                $.each(this.options.selectedItems, $.proxy(function (i, item) {
                    this._addOption(item);
                }, this));
            }
        },
        /**
         * If "multiselect" option is set, then do not need to clear value for hidden select, to avoid losing of
         *      previously selected items
         * @override
         */
        _resetSuggestValue: function () {
            if (!this.options.multiselect) {
                this._super();
            }
        },
        /**
         * @override
         */
        _createValueField: function () {
            if (this.options.multiselect) {
                return $('
', {
                    type: 'hidden',
                    multiple: 'multiple'
                });
            }
            return this._super();
        },
        /**
         * @override
         */
        _selectItem: function (e) {
            if (this.options.multiselect) {
                if (this._focused) {
                    this._selectedItem = this._focused;
                    /* eslint-disable max-depth */
                    if (this._selectedItem !== this._nonSelectedItem) {
                        this._term = '';
                        this.element.val(this._term);
                        if (this._isItemSelected(this._selectedItem)) {
                            $(e.target).removeClass(this.options.selectedClass);
                            this.removeOption(e, this._selectedItem);
                            this._selectedItem = this._nonSelectedItem;
                        } else {
                            $(e.target).addClass(this.options.selectedClass);
                            this._addOption(e, this._selectedItem);
                        }
                    }
                    /* eslint-enable max-depth */
                }
                this.close(e);
            } else {
                this._superApply(arguments);
            }
        },
        /**
         * @override
         */
        _isItemSelected: function (item) {
            if (this.options.multiselect) {
                return this.valueField.find('option[value=' + item.id + ']').length > 0;
            }
            return this._superApply(arguments);
        },
        /**
         *
         * @param {Object} item
         * @return {Element}
         * @private
         */
        _createOption: function (item) {
            var option = this._getOption(item);
            if (!option.length) {
                option = $('