require([
    "mage/translate",
    "jquery"
], function ($t, $) {

    'use strict';

    var resolutionSelect;
    var bundleSelected = null;

    var products = [];

    $(document).ready(function() {

        bindChebkboxes();

        easyReturnChange();

    });

    $(document).on('ajaxComplete', function (event, xhr, settings) {

        if (event.target.id !== 'order_items_grid') {
            return;

        }

        var interval = setInterval(function () {
            if ($('#rma_items_grid_table tbody.newRma').is(':visible') && $('#rma_items_grid_table tbody.newRma tr').length) {
                clearInterval(interval);
                addFormCell();
            }
        }, 1000)
    });

    var bindChebkboxes = function() {
        var items = $('#order_items_grid_table').find('.checkbox');
        items.on('change', function() {

            var id = $(this).attr('id').replace('id_', '');

            if (this.checked) {

                const item = getItemById(orderItems, id);

                if (item.product_type == 'bundle') {

                    console.debug(item.product.force_bundle_return);

                    if (item) {
                        if (item.product.force_bundle_return !== undefined && item.product.force_bundle_return == 1) {

                            console.debug('Bundle product selected');

                            var timer = setInterval(function () {
                                if ($('#all_items_' + id).length) {
                                    $('#individual_items_' + id).parent().hide();

                                    $('#all_items_' + id).parent().hide();
                                    $('#all_items_' + id).trigger('click');

                                    $('#bundle_div_' + id + ' input[type="checkbox"]').prop('readonly', 'readonly');
                                    $('#bundle_div_' + id + ' input[type="checkbox"]').prop('disabled', true);

                                    clearInterval(timer);
                                }
                            }, 200);
                        }
                    }
                }

                if (products.indexOf(id) === -1) {
                    products.push(id);
                }
            } else {
                let index = products.indexOf(id);
                if (index !== -1) {
                    products.splice(index, 1);  // Remove the first occurrence of the value
                }
            }
        });
    }

    var getItemById = function(items, itemId) {
        return items.find(item => String(item.item_id) === String(itemId));
    }

    var getItemByParentId = function(items, parentId) {
        return items.filter(item => String(item.parent_item_id) === String(parentId));
    }

    var getOrderItemIdBySku = function(sku) {
        var orderItemId = null;
        var orderItemsGridTable = $('#order_items_grid_table');
        $(orderItemsGridTable).find('tbody tr').each(function(index, tr) {
            $(tr).find('td').each(function(x, td) {
                if ($(td).text().trim() == sku) {
                    orderItemId = $(tr).find('input.checkbox').val();
                }
            })
        });

        return orderItemId;
    }

    var bindChangeToResolution = function(event) {

        calculateTheoricShippingAmount();

        if (!isChangeSizeEnabled) {
            return null;
        }

        var orderItemId = $(this).data('order-item-id')
        var rowIndex = $(this).data('order-index');
        var row = $(this).closest('tr');

        if (!orderItemId) {
            return;
        }

        var resolution = $(row).find('.col-resolution select').val();

        var postData = buildPostData(row, orderItemId)

        if (!postData) {
            return;
        }

        $.ajax({
            url: '/rest/V1/filoblu-rma/changesize',
            method: 'POST',
            contentType: "application/json",
            showLoader: true,
            data: JSON.stringify(postData),
            beforeSend: function(data) {

            }
        }).done(function(data) {

            if (!data.length) {
                clearChangeSizeSelect(row);
                return;
            }

            if (resolution != changeSizeOptionId) {
                clearChangeSizeSelect(row);
                return;
            }

            $(row).find('.col-changesize select option').remove();
            $(row).find('.col-changesize select').append($('<option></option>').attr('value', 0).text("-- Select --"));
            data.each(function(item, index) {
                $(row).find('.col-changesize select').append($('<option></option>').attr('value', item.value).text(item.text));
            });
            $(row).find('.col-changesize select').show();


            data.each(function(item, index) {
                if (!$(row).find('.field-change_size select option[value="'+item.value+'"]').length) {
                    $(row).find('.field-change_size select').append($('<option></option>').attr('value', item.value).text(item.text));
                }
            });
        })

        return;
    }

    var changeResolutionSuccessCallback = function(data, row) {

        var resolution = $(row).find('.col-resolution select').val();

        if (!data.length) {
            clearChangeSizeSelect(row);
            return;
        }

        if (resolution != changeSizeOptionId) {
            clearChangeSizeSelect(row);
            return;
        }

        $(row).find('.col-changesize select option').remove();
        $(row).find('.col-changesize select').append($('<option></option>').attr('value', 0).text("-- Select --"));
        data.each(function(item, index) {
            $(row).find('.col-changesize select').append($('<option></option>').attr('value', item.value).text(item.text));
        });
        $(row).find('.col-changesize select').show();


        data.each(function(item, index) {
            if (!$(row).find('.field-change_size select option[value="'+item.value+'"]').length) {
                $(row).find('.field-change_size select').append($('<option></option>').attr('value', item.value).text(item.text));
            }
        });
    }

    var changeReosoluiontErrorCallback = function(data) {

    }

    var addFormCell = function (table) {

        if (!isChangeSizeEnabled) {
            return;
        }

        var form = $('#rma_items_grid_table tbody.newRma');

        var items = $('#order_items_grid_table').find('.checkbox');
        if (!items.length) {
            return;

        }

        var _rma = this;

        var usedProducts = [];
        var bundleProducts = [];
        products.each(function(productId, index){
            var id = productId.replace('id_', '');
            const item = getItemById(orderItems, id);
            if (item.product_type == 'bundle') {
                var bundleItems = getItemByParentId(orderItems, id);
                bundleProducts.push(id);
                bundleItems.each(function(bundleItem, index) {
                    usedProducts.push(bundleItem.item_id);
                });
            } else {
                usedProducts.push(id);
            }

        });

        usedProducts.each(function(productId, index) {

            var checkbox = document.getElementById(productId);
            var id = '#id_new' + index;
            var row = form.find(id);

            resolutionSelect = $(row).find('.col-resolution select');

            if (!$(row).find('.col-changesize').length) {

                var sku = $(row).find('.col-product_sku').text();
                var orderItemId = getOrderItemIdBySku(sku);
                var isBundle = false

                const item = getItemById(orderItems, productId);

                if (bundleProducts.includes(item.parent_item_id)) {
                    $(row).addClass('bundle');
                    isBundle = true;
                }

                if (isBundle) {
                    var productName = $(row).find('td.col-product_sku').text();
                    $(row).find('td.col-product_sku').text(productName + "\n(Bundle Item)");
                }

                $(row).find('td.col-reason select').attr('data-order-item-id', orderItemId);
                $(row).find('td.col-reason select').attr('data-index', index);
                $(row).find('td.col-reason select').on('change', {'row': row, 'orderItemId': orderItemId}, reasonChange);


                $(row).find('td.col-resolution select').attr('data-order-item-id', orderItemId);
                $(row).find('td.col-resolution select').attr('data-index', index);
                $(row).find('td.col-resolution select').on('change', bindChangeToResolution);

                var changeSizeCell = $('<td class="col-changesize"><select id="rma_properties_change_size_new' + index + '" class="admin__control-select select admin__control-select" name="items[new' + index + '][change_size]" style="display: none"></select></td>')

                changeSizeCell.insertBefore($(row).find('.col-actions'))

                removeChangeSizeOptionIfProductIsBundle(row);

                $(row).find('td.col-changesize select').on('change', bindChangeSizeSelectAction);
                $(row).find('td.col-changesize select').attr('data-order-item-id', orderItemId);
                $(row).find('td.col-changesize select').attr('data-index', index);

                managePopup(row, index);

            } else {
                $(row).find('.col-changesize select').addClass('required-entry');
            }

        })
    }

    var buildPostData = function(row, orderItemId) {
        var qtyRequested = $(row).find('.col-qty_requested input').val();
        var reason = $(row).find('.col-reason select').val();
        var condition = $(row).find('.col-condition select').val();
        var resolution = $(row).find('.col-resolution select').val();

        if (!qtyRequested || !reason || !condition || !resolution) {
            return null;
        }

        var data = {
            "itemId": orderItemId,
            "qty": qtyRequested,
            "reason": reason,
            "resolution": resolution,
            "websiteId": websiteId,
            "form_key": window.FORM_KEY
        }

        return data;
    }

    var bindChangeSizeSelectAction = function() {
        var row = $(this).closest('tr');
        $(row).find('.popup-window-content select').val(this.value).change();
    }

    var managePopup = function(row, index) {
        $(row).find('.col-actions a').last().hide()
    }

    var clearChangeSizeSelect = function(row) {
        $(row).find('.col-changesize select option').remove();
        $(row).find('.col-changesize select').hide()
        $(row).find('.col-changesize select').removeClass('required-entry');
    }

    var reloadResolution = function(e) {

        var row = e.data.row;
        var orderItemId = e.data.orderItemId;
        var qty = $(row).find('.col-qty_requested input').val();
        var reason = $(row).find('.col-reason select').val();

        if (!reason) {
            return;
        }

        $.ajax({
            url: '/rest/V1/filoblu-rma/returnsAttributeWithAlternativesMetadata/itemId/'+orderItemId+'/qty/'+qty+'?reason_id='+reason,
            method: 'GET',
            contentType: "application/json",
            showLoader: true,
            beforeSend: function(data) {

            },
            success: function(data) {

                if (!data) {
                    return;
                }

                $(row).find('.col-resolution select option').remove();
                data.each(function(attribute,index) {
                    if (attribute.attribute_code == 'resolution') {
                        $(row).find('.col-resolution select').append($('<option selected="selected"></option>').attr('value', '').text(''));
                        attribute.options.each(function(option) {
                            $(row).find('.col-resolution select').append($('<option></option>').attr('value', option.value).text(option.label));
                        })
                    }
                });
            },
            error: function(jqXHR, textStatus, errorTh) {

            }
        })
    }

    var calculateTheoricShippingAmount = function() {

        if (!$('#filoblu_easy_return').val() || $('#filoblu_easy_return').val() == 0) {
            return;
        }

        var rmaItems = getRmaItems();

        if (!rmaItems.length) {
            return;
        }

        const data = {
            "data": {
                country_id: $("#filoblu_country_id").val(),
                region_id: $("#filoblu_region_id").val(),
                postcode: $("#filoblu_postcode").val(),
                city: $("#filoblu_city").val(),
                street: $("#filoblu_street").val(),
                add_currency: true,
                order_id: orderId,
                items: rmaItems
            }
        };

        $.ajax({
            url: '/rest/V1/filoblu-rma/estimatereturnshippingcost',
            method: 'POST',
            contentType: "application/json",
            showLoader: true,
            data: JSON.stringify(data),
            beforeSend: function (data) {

            },
            success: function (data) {
                $('#filoblu-theoric-shipping-amount').html('<span class="amount"><strong>Easy Return Shipping Cost</strong>: ' + data + '</span>');
            },
            error: function (jqXHR, textStatus, errorTh) {

            }
        });
    }

    var getRmaItems = function() {

        if (!$('#rma_items_grid_table').length) {
            return [];
        }

        if (!$('#rma_items_grid_table tbody tr td.col-product_name').length) {
            return [];
        }

        var items = [];

        $('#rma_items_grid_table tbody.newRma tr').each(function(){
            var tr = $(this);

            var orderItemId = $(tr).find('.col-actions > input').val();
            var qtyRequested = $(tr).find('.col-qty_requested input').val();
            var resolution = $(tr).find('.col-resolution select').val();

            if (!$(tr).find('.col-resolution select').val()) {
                return;
            }

            var item = {
                'order_item_id': orderItemId,
                'qty_requested': qtyRequested,
                'resolution': resolution
            }

            items.push(item)

        })

        return items;
    }

    var easyReturnChange = function() {

        if (!$('#filoblu_easy_return').length) {
            return;
        }

        var checked = $('#filoblu_easy_return').is(':checked') ? 1 : 0;
        $('#filoblu_easy_return').val(checked);

        toggleEasyReturnFields(checked);

        $('#filoblu_easy_return').on('change', function() {
            var checked = this.checked ? 1 : 0;
            this.value = checked;
            toggleEasyReturnFields(checked);
        })
    }

    var toggleEasyReturnFields = function(isChecked) {

        const container = $("#filoblu_address_fieldset");
        if ($(container).length) {

            $(container).hide();

            if (isChecked) {
                $(container).show();
            }
        }

        if (!isChecked || isChecked == 0) {
            $('#filoblu-theoric-shipping-amount').html('');
            return;
        }

        calculateTheoricShippingAmount();

    }

    var removeChangeSizeOptionIfProductIsBundle = function(row) {
        $(row).each(function(index, item) {
            if ($(item).hasClass('bundle')) {
                $(item).find('.col-resolution select option').each(function(i, option) {
                    if (option.value == changeSizeOptionId) {
                        $(option).remove();
                    }
                });
            }
        })
    }

    var reasonChange = function(e) {
        bindChangeToResolution(e);
        reloadResolution(e);
    }

});
