define([
    'jquery',
    'mage/template',
    'jquery/ui',
    'mage/translate'
], function ($, mageTemplate, ui, $t) {
    'use strict';

    $.widget('mage.rmaCreate', {

        /**
         * options with default values
         */
        options: {
            //Template defining selectors
            templateRegistrant: '#template-registrant',
            registrantOptions: '#registrant-options',
            changeSizeRegistran: '#',
            //Template selectors for adding and removing rows
            addItemToReturn: 'add-item-to-return',
            btnRemove: 'btn-remove',
            row: '#row',
            addRow: 'add-row',
            //Return item information selectors
            qtyReqBlock: '#qty_requested_block',
            remQtyBlock: '#remaining_quantity_block',
            remQty: '#remaining_quantity',
            reasonOtherRow: '#reason_other',
            reasonOtherInput: '#items:reason_other',
            radioItem: '#radio:item',
            orderItemId: '#item:order_item_id',
            itemsItem: 'items:item',
            changeSize: "items:change_size",
            itemsReason: 'items:reason',
            //Default counters and server side variables
            liIndex: 0,
            totalAvlQty: 0,
            availableQuantity: 0,
            formDataPost: null,
            firstItemId: null,
            productType: null,
            prodTypeBundle: null,
            propagation: false,
            changeSizeLabel: 'Change Size',
            enableProductIds: null,
            changeSizeOptionText: '',
            step2Button: '#confirm-returning-items',
            stepBackButton: '.go-back',
            step3Button: '#confirm-shipping-address',
            loadedOnce: false,
            rmaType: null
        },

        getBaseUrl: function () {
            return window.filoblu_rma_config.baseUrl
        },

        _getReasons: function () {
            return window.filoblu_rma_config.reasons ?? []
        },

        /**
         * Initialize rma create form
         * @private
         */
        _create: function () {
            //On document ready related tasks
            this._getChangeSizeLabel();
            $($.proxy(this._ready, this));
        },

        /**
         * Process and loop thru all form data to create "Items to return" with preselected value.
         * This is used for failed submit.
         * For first time this will add a default row without remove icon/button
         * @private
         */
        _ready: function () {

            this._processFormDataArr(this.options.formDataPost);
            //If no form data , then add default row for Return Item
            if (this.options.liIndex === 0) {
                this._addRegistrant();
                this._showOtherOption('', 0);
            }
            this._getChangeSizeEnableProducts();
            if ($("#simple-rma")) {
                $("#simple-rma").prop("checked", true);
            }
            this._getReturnShippingCost();
            $(document).ajaxComplete(function () {
                $('#region_id').prop('disabled', false);
                var hasValue = false;
                $('#region_id').find('option').each(function () {
                    if ($(this).attr('value')) {
                        hasValue = true;
                        if ($(this).attr('value') == 0 || $(this).attr('value') == 1) {
                            hasValue = false;
                        }
                    }
                });
                if ($('#region_id').find('option').length < 1 || hasValue == false) {
                    $('#region_id').next('.select2').hide();
                    $('#region_id').prop('disabled', true);
                    $('#region').prop('disabled', false);
                    if (!$('#region').attr('value')) {
                        $('#region').attr('value', $('#region_id').attr('data-default-region'));
                    }
                } else {
                    $('#region_id').next('.select2').show();
                    $('#region_id').prop('disabled', false);
                    $('#region').prop('disabled', true);
                }
            });

            this._handleStep1Changes();
            this._handleStep1ButtonClick();
            this._handleStepBack();
            this._handleReturnTypeSwitch();
            this._handleStep2();
        },

        /* eslint-disable */
        /* jscs:disable */
        /**
         * Parse form data and re-create the return item information row preserving the submitted values
         * @private
         * @param {Object} formDataArr
         */
        _processFormDataArr: function (formDataArr) {
            if (formDataArr) {
                var formDataArrlen = formDataArr.length;
                for (var i = 0; i < formDataArrlen; i++) {
                    //Add a row
                    this._addRegistrant();
                    //Set the previously selected values
                    for (var key in formDataArr[i]) {
                        if (formDataArr[i].hasOwnProperty(key)) {
                            if (key === 'order_item_id') {
                                this._setFieldById(this.options.itemsItem + i, formDataArr[i][key]);
                                this._showBundle(i, formDataArr[i][key]);
                                this._setFieldById(this.options.orderItemId.substring(1) + i + '_' + formDataArr[i][key]);
                            } else if (key === 'items') {
                                for (var itemKey in formDataArr[i][key]) {
                                    if (formDataArr[i][key].hasOwnProperty(itemKey)) {
                                        this._setFieldById('items[' + i + '][' + formDataArr[i].order_item_id + '][checkbox][item][' + itemKey + ']');
                                        this._setFieldById('items[' + i + '][' + formDataArr[i].order_item_id + '][checkbox][qty][' + itemKey + ']', formDataArr[i][key][itemKey]);
                                        this._setBundleFieldById(itemKey, formDataArr[i].order_item_id, i);
                                        delete formDataArr[i].qty_requested;
                                    }
                                }
                            } else if (key === 'qty_requested' && formDataArr[i][key] !== '') {
                                this._setFieldById('items:' + key + i, formDataArr[i][key]);
                            } else {
                                this._setFieldById('items:' + key + i, formDataArr[i][key]);

                                if (key === 'reason') {
                                    this._showOtherOption(formDataArr[i][key], i);
                                }
                            }
                        }
                    }
                }
            }
        },

        /* eslint-enable */
        /* jscs:enable */
        /**
         * Add new return item information row using the template
         * @private
         */
        _addRegistrant: function () {
            var self = this;

            this._setUpTemplate(this.options.liIndex, this.options.templateRegistrant, this.options.registrantOptions);
            this._showBundle(this.options.liIndex, this.options.firstItemId);
            this._showQuantity(this.options.productType, this.options.liIndex, this.options.availableQuantity);
            //Increment after rows are added
            this.options.liIndex++;

            this._handleStep1Changes();

            //PEUT-1868
            self._changeSize(false, 'items:resolution' + (this.options.liIndex - 1));

            self._canShowIbanForReturn();
        },

        /**
         * Remove return item information row
         * @private
         * @param {String} liIndex - return item information row index
         * @return {Boolean}
         */
        _removeRegistrant: function (liIndex) {
            var self = this;

            $(this.options.row + liIndex).remove();
            //this.options.liIndex--;

            self._canShowIbanForReturn();

            return false;
        },

        /**
         * Show bundle row for bundle product type
         * @private
         * @param {String} index - return item information row bundle index
         * @param {String} itemId - bundle item id
         */
        _showBundle: function (index, itemId) {
            var rItem, rOrderItemId, typeQty, position;

            $('div[id^="radio\\:item' + index + '_"]').each(function () {
                var $this = $(this);

                if ($this.attr('id')) {
                    $this.parent().hide();
                }
            });

            $('input[id^="items[' + index + ']"]').prop('disabled', true);

            rItem = $(this._esc(this.options.radioItem) + index + '_' + itemId);
            rOrderItemId = $(this._esc(this.options.orderItemId) + index + '_' + itemId);

            if (rItem.length) {
                rItem.parent().show();
                this._enableBundle(index, itemId);
            }

            if (rOrderItemId.length) {
                typeQty = rOrderItemId.attr('rel');
                position = typeQty.lastIndexOf('_');
                this._showQuantity(typeQty.substring(0, position), index, typeQty.substr(position + 1));
            }
        },

        /**
         * Show quantity block for bundled products
         * @private
         * @param {String} type - product type
         * @param {String} index - return item information row index
         * @param {String} qty - quantity of item specified
         */
        _showQuantity: function (type, index, qty) {
            var qtyReqBlock = $(this.options.qtyReqBlock + '_' + index),
                remQtyBlock = $(this.options.remQtyBlock + '_' + index),
                remQty = $(this.options.remQty + '_' + index);

            if (type === this.options.prodTypeBundle) {
                if (qtyReqBlock.length) {
                    qtyReqBlock.hide();
                }

                if (remQtyBlock.length) {
                    remQtyBlock.hide();
                }
            } else {
                if (qtyReqBlock.length) {
                    qtyReqBlock.show();
                }

                if (remQtyBlock.length) {
                    remQtyBlock.show();
                }

                if (remQty.length) {
                    remQty.text(qty);
                }
            }
        },

        /**
         * Enable bundle and its items
         * @private
         * @param {String} index - return item information row index
         * @param {String} bid - bundle type id
         */
        _enableBundle: function (index, bid) {
            $('input[id^="items[' + index + '][' + bid + '][checkbox][item]["]').prop('disabled', false);
            $('input[id^="items[' + index + '][' + bid + '][checkbox][qty]["]').prop('disabled', function () {
                return !this.value;
            });
        },

        /**
         * Set the value on given element
         * @private
         * @param {String} domId
         * @param {String} value
         */
        _setFieldById: function (domId, value) {
            var x = $('#' + this._esc(domId));

            if (x.length) {
                if (x.is(':checkbox')) {
                    x.attr('checked', true);
                } else if (x.is('option')) {
                    x.attr('selected', 'selected');
                } else {
                    x.val(value);
                }
            }
        },

        /**
         * Used to recreate bundle fields and pre select submitted values on server side errors
         * @private
         * @param {String} id
         * @param {String} bundleID
         * @param {String} index - return item information row index
         */
        _setBundleFieldById: function (id, bundleID, index) {
            this._showBundle(index, bundleID);
            this._showBundleInput(id, bundleID, index);
            this._showQuantity('bundle', index, 0);
        },

        /**
         * Toggle "Other" options
         * @private
         * @param {String} value
         * @param {(String|Number)} index - return item information row index
         */
        _showOtherOption: function (value, index) {
            var resOtherRow = this.options.reasonOtherRow,
                resOtherInput = this._esc(this.options.reasonOtherInput);

            if (value === 'other') {
                $(resOtherRow + index).show();
                $(resOtherInput + index).attr('disabled', false);
            } else {
                $(resOtherRow + index).hide();
                $(resOtherInput + index).attr('disabled', true);
            }
        },

        /**
         * Toggle bundled products
         * @param {String} id - bundle id
         * @param {String} bid - bundle type id
         * @param {String} index - return item information row index
         * @private
         */
        _showBundleInput: function (id, bid, index) {
            var qty = this._esc('#items[' + index + '][' + bid + '][checkbox][qty][' + id + ']');

            if ($(this._esc('#items[' + index + '][' + bid + '][checkbox][item][' + id + ']')).is(':checked')) {
                $(qty).show().attr('disabled', false);
            } else {
                $(qty).hide().attr('disabled', true);
            }
        },

        /**
         * Search for products to disabled from select (MNTFOS-203)
         * @param index - current index/count of the created template. This will be used as the id
         */
        _disableProductsFromSelection: function (index) {
            if (index !== 0) {
                var values = [];

                $('[name$="[order_item_id]"]').each(function (i, element) {
                    if (i !== index) {
                        values.push($(element).val());
                    } else {
                        var changed = false;

                        $("option", element).each(function (i, element2) {
                            if (values.includes($(element2).attr("value"))) {
                                $(element2).attr("disabled", ""); //can't remove it, do that to find out what happens
                            } else {
                                if (!changed) {
                                    $(element).val($(element2).attr("value")).change();
                                    changed = true;
                                }
                            }
                        });
                    }
                });
            }
        },

        /**
         * Initialize and create markup for Return Item Information row
         * using the template
         * @private
         * @param {String} index - current index/count of the created template. This will be used as the id
         * @param {String} templateId - template markup selector
         * @param {String} containerId - container where the template will be injected
         * @return {*}
         */
        _setUpTemplate: function (index, templateId, containerId) {
            var li = $('<div/>'),
                tmpl = mageTemplate(templateId);

            li.addClass('fields additional').attr('id', 'row' + index);

            tmpl = tmpl({
                data: {
                    _index_: index
                }
            });

            $(tmpl).appendTo(li);

            if ($(li).find('.nested.bundle-product').length > 0) {
                li.addClass('bundle-product');
            }

            $(containerId).append(li);

            // skipping first row
            if (index !== 0) {
                li.addClass(this.options.addRow);
            } else {
                //Hide the close button for first row
                $('#' + this.options.btnRemove + '0').hide();
            }

            this.element.on('change', 'select', function () {
                $('#region_id').prop('disabled', false);
                $('#region').prop('disabled', false);
                if ($('#region_id').css('display') == 'none') {
                    $('#region_id').prop('disabled', true);
                    $("#region_id").next('.select2').hide();
                } else {
                    $('#region').prop('disabled', true);
                    $("#region_id").next('.select2').show();
                }
            })

            //Binding template-wide events handlers
            this.element.on('change', "[id='country']", $.proxy(function () { this._getReturnShippingCost(); }, this));
            this.element.on('change', "[id='region_id']", $.proxy(function () { this._getReturnShippingCost(); }, this));
            this.element.on('change', "[id='filoblu-city']", $.proxy(function () { this._getReturnShippingCost(); }, this));
            this.element.on('change', "[id='zip']", $.proxy(function () { this._getReturnShippingCost(); }, this));
            this.element.on('click', 'button, input:checkbox', $.proxy(this._handleClick, this))
                .on('change', '#registrant-options select:not([id^="items:condition"])', $.proxy(this._handleChange, this))
                .on('keyup', 'input.input-text', $.proxy(this._handleKeyup, this));

            //init change_size visibility
            $("div[class^='field change_size" + index + "']").addClass('hidden');

            this._disableProductsFromSelection(index);

            return li;

        },

        /**
         * Recount remaining quantity for requested bundle items
         * @private
         * @return {integer}
         */
        _recountBundleRemQty: function () {
            var items = {},
                totalReqQty = 0,
                collection = $('.nested input[type="checkbox"]');

            collection.filter(':checked').each(function () {
                var itemId = $(this).data('args').item,
                    itemIndex = $(this).data('args').index,
                    bundleId = $(this).data('args').bundleId,
                    initialQty = $(this).data('args').initialQty,
                    itemReqInput = $('[id="items[' + itemIndex + '][' + bundleId + '][checkbox][qty][' + itemId + ']"]'),
                    itemReqQty = itemReqInput.val() * 1;

                if (itemReqQty < 0) {
                    itemReqQty = 0;
                }

                if (typeof items[itemId] === 'undefined') {
                    items[itemId] = itemReqQty;
                } else {
                    var totalBundleIdReqQty = items[itemId],
                        maxAllowedBundleIdReqQty = initialQty - totalBundleIdReqQty;

                    if (itemReqInput.val() > maxAllowedBundleIdReqQty) {
                        itemReqInput.val(maxAllowedBundleIdReqQty);
                    }

                    items[itemId] += Math.min((totalBundleIdReqQty + itemReqQty), maxAllowedBundleIdReqQty);
                }
            });

            collection.each(function () {

                var itemId = $(this).data('args').item,
                    initialQty = $(this).data('args').initialQty,
                    remQtyColElem = $(this).closest('tr').find('.remaining.qty'),
                    itemReqQty = 0;

                if (typeof items[itemId] !== 'undefined') {
                    itemReqQty = items[itemId];
                }

                remQtyColElem.text(initialQty - itemReqQty);
            });

            $.each(items, function (itemId, itemReqQty) {
                totalReqQty += itemReqQty;
            });

            return totalReqQty;
        },

        /**
         * Recount remaining quantity for requested simple items
         * @private
         * @return {integer}
         */
        _recountSimpleRemQty: function () {
            var items = {},
                totalReqQty = 0,
                options = this.options,
                collection = $('select[id^="' + options.itemsItem + '"]').not('[id="items:item<%- data._index_ %>"]');

            collection.each(function () {
                var itemId = $(this).val(),
                    itemIndex = $(this).data('args').index,
                    itemReqQty = $('[id="items:qty_requested' + itemIndex + '"]').val() * 1;

                if (typeof items[itemId] === 'undefined') {
                    items[itemId] = itemReqQty;
                } else {
                    items[itemId] += itemReqQty;
                }
            });

            collection.each(function () {
                var itemId = $(this).val(),
                    itemIndex = $(this).data('args').index,
                    itemAvlQty = $(this).find(':selected').attr('rel').split('_')[1];

                if (typeof items[itemId] !== 'undefined') {
                    $(options.remQty + '_' + itemIndex).text(itemAvlQty - items[itemId]);
                }
            });

            $.each(items, function (itemId, itemReqQty) {
                totalReqQty += itemReqQty;
            });

            return totalReqQty;
        },

        /**
         * Recount remaining quantity for all requested items
         * @private
         */
        _recountRemQty: function () {
            var orderTotalRemQty = this.options.totalAvlQty;

            orderTotalRemQty -= this._recountSimpleRemQty();
            orderTotalRemQty -= this._recountBundleRemQty();

            // Disabling 'Add Item To Return' button if there are no more items available.
            if (orderTotalRemQty > 0) {
                $('#' + this.options.addItemToReturn).prop('disabled', false);
            } else {
                $('#' + this.options.addItemToReturn).prop('disabled', true);
            }
        },

        /* eslint-disable max-depth*/
        /**
         * Delegated handler for click
         * @private
         * @param {Object} e - Native event object
         * @return {Null|Boolean}
         */
        _handleClick: function (e) {
            var currElem = $(e.currentTarget),
                args;

            if (currElem.attr('id') === this.options.addItemToReturn) {
                if (e.handled !== true) {
                    this._addRegistrant();
                    this._recountRemQty();
                    e.handled = true;
                    return false;
                }

            } else if (currElem.hasClass(this.options.btnRemove)) {
                //Extract index
                this._removeRegistrant(currElem.parent().attr('id').replace(this.options.btnRemove, ''));
                this._recountRemQty();
                if (!this.options.propagation) {
                    this.options.liIndex--;
                    this.options.propagation = !this.options.propagation;
                }

                //fire handleSubmitBtnStatus()
                this._handleSubmitBtnStatus()

                return false;
            } else if (currElem.attr('type') === 'checkbox') {
                if (currElem.attr('id').match(/^items/)) {
                    args = currElem.data('args');

                    if (args) {
                        this._showBundleInput(args.item, args.bundleId, args.index);
                    }

                    if (currElem.prop('checked') === false) {
                        currElem.closest('tr').find('input[type="number"]').val(0);
                    }

                    this._recountRemQty();
                }
            }
        },

        /**
         * Show/hide the given return type tab
         * @param {String} action - "show" or "hide"
         * @param {String} key - Return type tab key
         */
        _showHideReturnTypeTab: function (action, key) {
            if (action && ["show", "hide"].includes(action) && key) {
                var element = $(`.${key}-return`, ".order-links");

                if (element.length) {
                    if (action == "show") {
                        if (element.hasClass("hide")) {
                            element.removeClass("hide");
                        }
                    } else if (action == "hide") {
                        if (!element.hasClass("hide")) {
                            element.addClass("hide");
                        }
                    }
                }
            }
        },

        /**
         * Get available return types based on items to return
         * @param {Object} items - Items to return
         */
        _getReturnTypes: function () {
            var self = this,
                data = [],
                errorElement = $(".return-types-error");

            $(".fields", "#registrant-options").each((index, item) => {
                data.push({
                    order_item_id: $('[name$="[order_item_id]"]', item).val(),
                    resolution: $('[name$="[resolution]"]', item).val(),
                });
            });

            $.ajax({
                data: {
                    items: data,
                },
                url: self.getBaseUrl() + "filoblurma/index/getreturntypes",
                beforeSend: function () {
                    $("body").trigger("processStart");
                },
                complete: function () {
                    $("body").trigger("processStop");
                },
                error: function () {
                    if (errorElement.hasClass("hide")) {
                        errorElement.removeClass("hide");
                    }
                },
                success: function (response) {
                    if (response?.data) {
                        if (!errorElement.hasClass("hide")) {
                            errorElement.addClass("hide");
                        }

                        if (response.data.normal_return) {
                            self._showHideReturnTypeTab("show", "normal");
                        } else {
                            self._showHideReturnTypeTab("hide", "normal");
                        }

                        if (response.data.easy_return) {
                            self._showHideReturnTypeTab("show", "easy");
                        } else {
                            self._showHideReturnTypeTab("hide", "easy");
                        }

                        var countrySelect = $("[name='country_id']", ".step-2");

                        $(".step-1", "#rma_create_form").hide(0, function () {
                            $(".step-2", "#rma_create_form")
                                .removeClass("hide")
                                .show(0, function () {
                                    $("html, body").scrollTop(
                                        $(".step-2", "#rma_create_form").offset().top - $(".page-header").height()
                                    );

                                    if ($("#rma_create_form").valid()) {
                                        $(self.options.step3Button).removeAttr("disabled");
                                    } else {
                                        $(self.options.step3Button).attr("disabled", true);
                                    }

                                    self._getReturningItemsTable();
                                });
                        });

                        if (countrySelect.length && !countrySelect.attr("disabled")) {
                            countrySelect.attr("disabled", true);
                        }
                    } else {
                        self._showHideReturnTypeTab("hide", "normal");
                        self._showHideReturnTypeTab("hide", "easy");
                    }
                },
            });
        },

        /* eslint-enable max-depth*/
        /**
         * Delegated handler for change
         * @private
         * @param {Object} e - Native event object
         */
        _handleChange: function (e) {
            var currElem = $(e.currentTarget),
                currId = currElem.attr('id'),
                args = currElem.data('args');

            $('.no-sizes-available').remove();

            this._changeSize(e, currId);

            if (args && currId) {
                if (currId.substring(0, 10) === this.options.itemsItem) {
                    currElem.parent().find('input[type="checkbox"]').prop('checked', false);
                    currElem.parent().find('input[type="number"]').val('');
                    currElem.closest('fieldset').find('[id^="items:qty_requested"]').val(0);

                    this._showBundle(args.index, currElem.val());
                } else if (currId.substring(0, 12) === this.options.itemsReason) {
                    this._showOtherOption(currElem.val(), args.index);
                }

                this._recountRemQty();

                return false;
            }

        },

        /**
         * Delegated handler for keyup
         * @private
         * @param {Object} e - Native event object
         */
        _handleKeyup: function (e) {
            var currElem = $(e.currentTarget),
                currElemId = currElem.attr('id'),
                currElemContainer = currElem.closest('fieldset').find('select[id^="' + this.options.itemsItem + '"]'),
                currElemIndex, orderItemRemQty, orderItemReqQty;

            this._changeSize(e, currElemId);

            if (currElemContainer.length < 1) {
                currElemContainer = currElem.closest('fieldset')
                    .siblings('fieldset').find('select[id^="' + this.options.itemsItem + '"]');
            }
            currElemIndex = currElemContainer.data('args').index;

            if (currElemId.match(/^items/) && !e.handled) {
                this._recountRemQty();

                orderItemRemQty = 0;
                orderItemReqQty = parseInt(currElem.val(), 10);

                if (currElem.closest('tr').find('.remaining.qty').length > 0) {
                    orderItemRemQty = parseInt(currElem.closest('tr').find('.remaining.qty').text(), 10);
                } else {
                    orderItemRemQty = parseInt($('[id^="remaining_quantity_' + currElemIndex + '"]').text(), 10);
                }

                if (orderItemRemQty < 0) {
                    currElem.val(orderItemReqQty + orderItemRemQty);
                    this._recountRemQty();
                }

                e.handled = true;
            }
        },

        /**
         * Utility function to add escape chars for jquery selector strings
         * @private
         * @param {String} str - String to be processed
         * @returns {String}
         */
        _esc: function (str) {
            if (str) {
                return str.replace(/([ ;&,.+*~\':"!\^$\[\]()=>|\/@])/g, '\\$1');
            }

            return str;
        },

        _getChangeSizeOptionId: function () {
            return window.filoblu_rma_config.changeSizeOptionId
        },

        _isChangeSizeResolution: function (resolutionId) {
            return this._getChangeSizeOptionId() == resolutionId
        },

        _handleResolutionChange: function (itemId) {

            if (!this._getReasons() || this._getReasons().length <= 0) {
                return;
            }

            var resolutionSelect = document.getElementById(`items:resolution${itemId}`);
            var reasonSelect = document.getElementById(`items:reason${itemId}`);
            var selected = reasonSelect.value;
            var optionToApply = this._getReasons().default;

            if (this._isChangeSizeResolution(resolutionSelect.value)) {
                optionToApply = this._getReasons().change_size
            }

            this._canShowIbanForReturn();

            while (reasonSelect.options.length) {
                reasonSelect.remove(0)
            }

            $.each(optionToApply, function (key, reason) {
                reasonSelect.add(new Option(reason.label, reason.value, key === 0, selected === reason.value));
            })
        },

        _changeSize: function (e, id) {

            var self = this,
                form = self.element,
                selector = '',
                reloadRequired = false;

            switch (true) {

                case id.search('items:item') >= 0:
                    selector = 'items:item';
                    reloadRequired = true;
                    break;
                case id.search('items:resolution') >= 0:
                    selector = 'items:resolution';
                    self._handleResolutionChange(id.replace(selector, ''))
                    reloadRequired = true;
                    break;
                case id.search('items:qty_requested') >= 0:
                    selector = 'items:qty_requested';
                    reloadRequired = true;
                    break;
                case id.search('items:condition') >= 0:
                    selector = 'items:condition';
                    reloadRequired = false;
                    break;
                case id.search('items:reason') >= 0:
                    selector = 'items:reason';
                    reloadRequired = true;
                    break;
                case id.search('items:change_size') >= 0:
                    selector = 'items:change_size';
                    reloadRequired = false;
                    break;
                // case id.search('items:iban_for_return') >= 0:
                //     selector = 'items:iban_for_return';
                //     reloadRequired = false;
                //     break;
                default:
                    return;
            }

            var itemId = id.replace(selector, '');
            var product = document.getElementById('items:item' + itemId).value;
            var resolution = document.getElementById('items:resolution' + itemId).value;
            var qty = document.getElementById('items:qty_requested' + itemId).value;
            var reason = document.getElementById('items:reason' + itemId).value;

            qty = parseInt(qty);

            if (qty <= 0 || isNaN(qty)) {
                qty = 1;
                document.getElementById('items:qty_requested' + itemId).value = 1;
            }

            if (resolution === "") {
                resolution = 0;
            }

            if (self.options.rmaType == null) {
                self.options.rmaType = $('.field.resolution' + itemId + ' select').parent().html();
            }

            if (reloadRequired === true) {
                var sizeOptions = document.getElementById('items:change_size' + itemId).options;
                //re-init select
                for (var i = 0; i < sizeOptions.length; i++) {
                    sizeOptions.remove(i);
                }
                var http = new XMLHttpRequest();
                var websiteId = window.filoblu_rma_config.websiteId;
                //var params = [product, resolution, qty];

                if (this.options.enableProductIds && this.options.enableProductIds.indexOf(product) === -1) {
                    $("div[class^='field change_size" + id.replace(selector, '') + "']").addClass('hidden');
                    //re-init select
                    if (document.getElementById('items:change_size' + itemId)) {
                        document.getElementById('items:change_size' + itemId).innerHTML = '';
                    }

                    if (this._isChangeSizeResolution(document.getElementById('items:resolution' + itemId).value) && $('.field.change_size' + itemId).is(':hidden')) {
                        $('<div class="no-sizes-available">' + $t('No sizes available. Pelase select a different return type.') + '</div>').insertAfter($('.field.change_size' + itemId));
                    }

                    self._handleResolutionChange(id.replace(selector, ''));
                    self._handleSubmitBtnStatus();
                    return;
                }

                var baseUrl = this.getBaseUrl();
                var iban_required_for_rma = true;


                //get available resolutions
                var url = baseUrl + 'rest/V1/filoblu-rma/returnsAttributeWithAlternativesMetadata/itemId/' + product + '/qty/' + qty + '?reason_id=' + reason;
                var http2 = new XMLHttpRequest();
                http2.open('GET', url);
                http2.setRequestHeader("Content-Type", "application/json");
                http2.casa = this;
                http2.onreadystatechange = function () {

                    if (http2.readyState == 4 && http2.status == 200) {
                        var data = JSON.parse(http2.responseText);

                        $('.field.resolution' + itemId + ' select').empty();

                        var selected = '';

                        data.forEach(function (item) {
                            if (item.attribute_code == 'resolution') {
                                item.options.forEach(function (option) {
                                    if (option.value == resolution) {
                                        iban_required_for_rma = option.iban_required_for_rma;
                                        selected = 'selected';
                                    } else {
                                        selected = '';
                                    }
                                    var option = '<option value="' + option.value + '" ' + selected + '>' + option.label + '</option>';
                                    $('.field.resolution' + itemId + ' select').append($(option));
                                })
                            }
                        })

                        //get available products for change
                        var url = baseUrl + '/rest/V1/filoblu-rma/changesize?itemId=' + product + '&qty=' + qty + '&resolution=' + resolution + '&reason=' + reason + '&websiteId=' + websiteId;
                        http.open('POST', url);
                        http.setRequestHeader("Content-Type", "application/json");

                        http.casa = this;
                        http.onreadystatechange = function () {

                            if (http.readyState == 4 && http.status == 200) {

                                var sizeData = JSON.parse(http.responseText);

                                var options = '';

                                if (sizeData[0]?.value === 0) { //no available sizes
                                    $(self.options.step2Button).attr("disabled", true);
                                }

                                var changeSizeField = $('.field.change_size' + itemId);
                                changeSizeField.find('.no-sizes-available').remove();

                                if (!sizeData.length) {
                                    changeSizeField.children().hide();
                                    //$('.field.resolution' + itemId + ' option[value="' + self._getChangeSizeOptionId() + '"]').remove();
                                    resolution = document.getElementById('items:resolution' + itemId).value;
                                } else {
                                    changeSizeField.children().show();

                                    resolution = document.getElementById('items:resolution' + itemId).value;

                                }

                                if (resolution != self._getChangeSizeOptionId()) {
                                    changeSizeField.hide();

                                    if (qty > 0 && $(form).validation('isValid')) {
                                        $(self.options.step2Button).removeAttr("disabled");
                                    } else {
                                        $(self.options.step2Button).attr("disabled", true);
                                    }

                                    changeSizeField.find('.no-sizes-available').remove();

                                } else {
                                    changeSizeField.show();
                                    if (!sizeData.length) {
                                        $(self.options.step2Button).attr("disabled", true);
                                    }

                                    // $('#iban_for_return' + itemId).removeClass('required').hide();
                                }
                                // if (iban_required_for_rma) {
                                //     $('#iban_for_return' + itemId).addClass('required').show();
                                // } else {
                                //     $('#iban_for_return' + itemId).removeClass('required').hide();
                                // }

                                if ($('.no-sizes-available').length) {
                                    $(self.options.step2Button).attr("disabled", true);
                                }

                                for (var i = 0; i < sizeData.length; i++) {
                                    var selected = '';
                                    if (i == 0) {
                                        selected = 'selected';
                                    }
                                    options += '<option value="' + sizeData[i].value + '"' + selected + '>' + sizeData[i].text + '</option>';

                                    if ($(".normal-return", ".order-links").hasClass("current")) {
                                        $("a", ".order-links").trigger("click");
                                    }
                                }

                                document.getElementById('items:change_size' + itemId).innerHTML = options;
                                $("div[class^='field change_size" + id.replace(selector, '') + "']").removeClass('hidden');
                                $('body').trigger('processStop');
                                //change Sumbmit status
                                http2.casa._handleSubmitBtnStatus();
                            }
                        }
                        http.send();

                    }
                }

                if (reason) {
                    $('body').trigger('processStart');
                    http2.send();
                    return
                }
                return
            }

            if (selector == 'items:resolution') {
                $("div[class^='field change_size" + itemId + "']").addClass('hidden');
                //re-init select
                if (document.getElementById('items:change_size' + itemId)) {
                    document.getElementById('items:change_size' + itemId).innerHTML = '';
                }
            }

            this._handleSubmitBtnStatus();

        },


        _handleSubmitBtnStatus: function () {

            var sizeNotAvailable = false,
                self = this,
                form = self.element;

            for (var i = 0; i < this.options.liIndex; i++) {
                if (document.getElementById('items:change_size' + i)) {
                    var el = document.getElementById('items:change_size' + i);
                    for (var b = 0; b < el.options.length; b++) {
                        if (el.options[b].value == 0) {
                            sizeNotAvailable = true;
                        }
                    }
                }
            }

            if ($('.no-sizes-available').length) {
                sizeNotAvailable = true;
                $(this.options.step2Button).attr("disabled", true);
            } else {

                if ($(form).validation('isValid')) {
                    $(this.options.step2Button).removeAttr("disabled");
                }

            }

            document.getElementById('submit.save').disabled = sizeNotAvailable;
        },

        _getChangeSizeLabel: function () {
            var http = new XMLHttpRequest();
            http.casa = this;


            var url = this.getBaseUrl() + '/rest/V1/filoblu-rma/getlabel';
            http.open('POST', url);
            http.setRequestHeader('Content-Type', 'application/json');
            $('body').trigger('processStart');

            http.onreadystatechange = function () {

                if (http.readyState == 4 && http.status == 200) {
                    http.casa.options.changeSizeLabel = JSON.parse(http.responseText);
                    $('body').trigger('processStop');
                    http.casa.__saveChangeSizeOptionText();
                }
            }
            http.send();
        },
        _getReturnShippingCost: function () {
            //alert('started get return shipping costs');
            var http = new XMLHttpRequest();
            http.casa = this;

            var city = $('#filoblu-city').val() ?? '';
            var region_id = $('#region').val() ?? '';
            var postcode = $('#zip').val() ?? '';
            var country_id = $('#country').val() ?? '';
            var num_items = $('[id^="items:qty_requested"]').length ?? 0;

            if (num_items > 0 && ('#simple-rma') && $('#simple-rma').is(':checked')) {
                var items = [];
                for (let i = 0; i < num_items; i++) {
                    var order_item_id = $('[id="items:item' + i + '"').val() ?? 0;
                    var qty_requested = $('[id="items:qty_requested' + i + '"').val() ?? 1;
                    var condition = $('[id="items:condition' + i + '"').val();
                    var reason = $('[id="items:reason' + i + '"').val();
                    var resolution = $('[id="items:resolution' + i + '"').val();

                    items.push({
                        'order_item_id': order_item_id,
                        'condition': condition,
                        'reason': reason,
                        'resolution': resolution,
                        'qty_requested': qty_requested
                    });
                }
                var data = {
                    'data': {
                        'city': city,
                        'region_id': region_id,
                        'postcode': postcode,
                        'country_id': country_id,
                        'items': items
                    }
                };

                var orderId = $('#rma_create_form').data('order-id')

                var url = this.getBaseUrl() + '/rest/V1/filoblu-rma/estimatereturnshippingcost?order_id=' + orderId;
                http.open('POST', url, true);
                http.setRequestHeader('Content-Type', 'application/json');
                $('body').trigger('processStart');

                http.onreadystatechange = function () {

                    if (http.readyState === 4 && http.status === 200) {
                        //update field on frontend
                        $(".simple-rma-message").html(JSON.parse(http.responseText));

                        //alert(JSON.parse(http.responseText));
                        $('body').trigger('processStop');
                    }
                }
                http.send(JSON.stringify(data));
            }
        },

        __saveChangeSizeOptionText: function () {
            var resolutionSelect = document.getElementById('items:resolution0');

            for (var i = 0; i < resolutionSelect.options.length; i++) {
                if (resolutionSelect.options[i].value == this.options.changeSizeLabel) {
                    this.options.changeSizeOptionText = resolutionSelect.options[i].text;
                }
            }
        },

        _getChangeSizeEnableProducts: function () {
            var self = this;
            var http = new XMLHttpRequest();
            http.casa = this;
            var select = document.getElementById('items:item0').options;
            var productIds = new Array();

            for (var i = 0; i < select.length; i++) {
                productIds.push(select[i].value);
            }

            // if (productIds.length) {
            //     return;
            // }

            var websiteId = window.filoblu_rma_config.websiteId;
            var url = this.getBaseUrl() + '/rest/V1/filoblu-rma/getChangeSizeEnabledProducts?productIds=' + productIds + '&websiteId=' + websiteId;
            http.open('POST', url);
            http.setRequestHeader('Content-Type', 'application/json');
            $('body').trigger('processStart');

            // var shouldSend = false;

            http.onreadystatechange = function () {

                if (http.readyState == 4 && http.status == 200) {
                    http.casa.options.enableProductIds = JSON.parse(http.responseText);

                    $('body').trigger('processStop');

                    //PEUT-1868
                    setTimeout(function () {
                        if (!self.loadedOnce) {
                            $('select[id^="items:resolution"]').each(function (index, element) {
                                self._changeSize(false, element.id);
                            });

                            self.loadedOnce = true;
                        }
                    });
                }
            }
            http.send();
        },

        _handleStep1Changes: function () {
            var self = this,
                form = this.element,
                fieldsToValidate = $('input, select', '#registrant-options'),
                ibanForReturnField = $('#iban_for_return');

            fieldsToValidate.on('change keyup', function () {
                if ($(form).validation('isValid')) {
                    $(self.options.step2Button).removeAttr('disabled');
                } else {
                    $(self.options.step2Button).attr('disabled', true);
                }
            });

            if (ibanForReturnField.length) {
                ibanForReturnField.on('change keyup', function () {
                    if ($(form).validation('isValid')) {
                        $(self.options.step2Button).removeAttr('disabled');
                    } else {
                        $(self.options.step2Button).attr('disabled', true);
                    }
                });
            }
        },

        _handleStep1ButtonClick: function () {
            var self = this;

            $(this.options.step2Button).on('click', function () {
                self._getReturnTypes();
                /*
                    Do _getReturnShippingCost() because you could add more items
                    or change their reason/resolution type
                    and in next step only confirm your shipping data
                    (in that case, the data object will no longer be updated).
                */
                self._getReturnShippingCost();

                // Fill iban_for_return field for all items that need it
                self._fillItemIbanField();
            });
        },

        _getReturningItemsTable: function () {
            var html = "<div>",
                iban = $("#iban_for_return"),
                isIbanVisible = iban.length ? $("#iban-for-return-wrapper").css("display") != "none" : false,
                comment = $("#rma_comment").val();

            $(".returning-items-summary", "#rma_create_form").empty();

            $(".fields.additional", "#registrant-options").each(function (index, element) {
                html += "<div class='item'>";

                if ($(element).hasClass('bundle-product')) {
                    $("select, input", element).each(function (index, element2) {

                        if ($(element2).is("input") && typeof $(element2).data("args") === 'undefined') {
                            return true;
                        }

                        var field = element2.closest('.field'),
                            label = "",
                            value = "";

                        if ($(element2).is("select")) {
                            label += $("label", $(element2).parents(".field"))[0].textContent;
                            value += $("option:selected", element2).text();
                        }

                        if ($(element2).is("input") && typeof $(element2).data("args").bundleItemName !== 'undefined') {
                            if ($(element2).val() > 0) {
                                label += $(element2).data("args").bundleItemName;
                                value += $(element2).val();
                            }
                        }

                        if (value && $(field).css("display") !== "none") {

                            html += "<div><strong>" + label + "</strong>: " + value + "</div>";
                        }
                    });
                }
                else {
                    $("select, input", element).each(function (index, element2) {
                        var value = $(element2).is("select") ? $("option:selected", element2).text() : $(element2).val(),
                            field = element2.closest('.field');

                        if (value && $(field).css("display") !== "none") {
                            var label = $("label", $(element2).parents(".field")).text();

                            html += "<div><strong>" + label + "</strong>: " + value + "</div>";
                        }
                    });
                }

                html += "</div>";
            });

            if (iban.length && isIbanVisible) {
                var ibanValue = iban.val();
                html += "<div class='iban-for-return-label'><strong>" + $("label[for='iban_for_return']").text() + "</strong>: " + ibanValue + "</div>";
            }

            if (comment) {
                html += "<div class='comment'><strong>" + $("label[for='rma_comment']").text() + "</strong> : " + comment + "</div>";
            }

            html += "</div>";

            $(".returning-items-summary").append(html);
        },

        _handleStepBack: function () {
            $(this.options.stepBackButton).on("click", function (event) {
                var target = $(event.target).is("button") ? $(event.target) : $(event.target).parent(),
                    currentStep = target.data("step"),
                    destination = target.data("target");

                $(currentStep, "#rma_create_form").hide(0, function () {
                    $(destination, "#rma_create_form").show(0, function () {
                        $("html, body").scrollTop($(destination, "#rma_create_form").offset().top - $('.page-header').height());
                    });
                });
            });
        },

        _handleReturnTypeSwitch: function () {
            $(".step-2 .order-links").on("click", "a", function (event) {
                var target = $(event.target),
                    parent = target.parent();

                event.preventDefault();
                parent.addClass("current");
                parent.html("<strong>" + target.text().trim() + "</strong>");

                if (parent.index() === 0) {
                    var nextElement = parent.next();

                    nextElement.removeClass("current");
                    nextElement.html("<a href='#'>" + nextElement.text().trim() + "</strong>");
                } else {
                    var prevElement = parent.prev();

                    prevElement.removeClass("current");
                    prevElement.html("<a href='#'>" + prevElement.text().trim() + "</strong>");
                }

                if (parent.hasClass("normal-return")) {
                    $(".contents", ".step-2").addClass("translated");
                    $("#normal-rma").prop("checked", true).change();
                    $("#simple-rma").closest('.fieldset-easy-return').hide();
                } else {
                    $(".contents", ".step-2").removeClass("translated");
                    $("#simple-rma").prop("checked", true).change();
                    $("#simple-rma").closest('.fieldset-easy-return').show();
                }
            });
        },

        _handleStep2: function () {
            var self = this,
                form = self.element;

            $("select, input", ".step-2 .fieldset").on("change", function () {
                if ($(form).validation("isValid")) {
                    $(self.options.step3Button).removeAttr("disabled");
                } else {
                    $(self.options.step3Button).attr("disabled", true);
                }
            });

            $(this.options.step3Button).on("click", function () {
                var html = "";

                $("body").trigger("processStart");
                $(".return-type-summary", "#rma_create_form").empty();

                $("select, input:not([name='return_type'])", ".step-2 .fieldset").each(function (index, element) {
                    var value = $(element).is("select") ? $("option:selected", element).text() : $(element).val();

                    if (value && $(element).attr("value")) {
                        var label = $("label", $(element).parents(".field")).text();

                        html += "<div><strong>" + label + "</strong>: " + value + "</div>";
                    }
                });

                $(".return-type-summary", "#rma_create_form").append(html);

                $(".step-2", "#rma_create_form").hide(0, function () {
                    $(".step-3", "#rma_create_form").removeClass("hide").show(0, function () {
                        $("html, body").scrollTop($("#rma_create_form").offset().top - $('.page-header').height());
                    });
                });

                $("body").trigger("processStop");
            });
        },

        _canShowIbanForReturn: function () {

            if (!$(document.getElementById('iban-for-return-wrapper')).length) {
                return false;
            }

            var self = this,
                canShowIbanForReturn = false,
                resolutions = $(document.querySelectorAll('[id^="items:resolution"]'));

            $.each(resolutions, function (key, resolution) {
                // If at least one resolution isn't a change size type, then show iban (because it's a refund!)
                if (!self._isChangeSizeResolution(resolution.value)) {
                    canShowIbanForReturn = true;
                    return false;
                }
            });

            if (canShowIbanForReturn) {
                $(document.getElementById('iban-for-return-wrapper')).show();
            }
            else {
                $(document.getElementById('iban-for-return-wrapper')).hide();
                // Clear iban field if no one refund resolution
                $("#iban_for_return").val("");
            }
        },

        _fillItemIbanField: function () {

            if (!$(document.getElementById('iban-for-return-wrapper')).length) {
                return false;
            }

            var self = this,
                ibanForReturnField = $('#iban_for_return'),
                resolutions = $(document.querySelectorAll('[id^="items:resolution"]'));

            $.each(resolutions, function (key, resolution) {
                if (!self._isChangeSizeResolution(resolution.value)) {
                    // Add iban to product details
                    document.getElementById("items:iban_for_return" + key).value = ibanForReturnField.val();
                }
            });
        }
    });

    return $.mage.rmaCreate;
});
