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

    'use strict';

    var resolutionSelect;

    var products = [];

    $(document).ready(function() {
        var items = $('#order_items_grid_table').find('.checkbox');
        items.change(function() {
            var id = $(this).attr('id');
            if (this.checked) {
                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
                }
            }
        })
    });

    $(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();
            }
        }, 2000)
    });

    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) {

        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;

        products.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);

                $(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 required-entry" name="items[new' + index + '][change_size]" style="display: none"></select></td>')

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

                $(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 reasonChange = function(e) {
        bindChangeToResolution(e);
        reloadResolution(e);
    }

});
