jQuery(function ($) {

    $(document).on('click', '.payout-item-preview:not(.disabled)', function (e) {

        e.preventDefault();
        var $previewButton = $(this),
            $payout_item_id = $previewButton.data('id');


        if ($previewButton.data('payout-data')) {
            var template = wp.template('yith-payouts-modal-view-payout-item');
            template = $(template($previewButton.data('payout-data')));
            var header = template.find('.wc-backbone-modal-header');
            template.remove('.wc-backbone-modal-header');
            yith.ui.modal(
                {
                    'width': 500,
                    'title': header,
                    'content': template,
                    'footer': false,
                    'scrollContent': true,
                    'classes': {
                        content: 'wc-backbone-modal wc-payout-item-preview wc-order-preview',
                        title: 'yith-payout-item-title',
                    },
                    allowClosingWithEsc: true,
                    closeWhenClickingOnOverlay: true
                });

        } else {
            $previewButton.addClass('disabled');

            $.ajax({
                url: payouts_modal.admin_url,
                data: {
                    payout_item_id: $payout_item_id,
                    action: payouts_modal.actions.payouts_get_payout_item_details,

                },
                type: 'GET',
                success: function (response) {
                    $('.payout-item-preview').removeClass('disabled');

                    if (response.success) {
                        $previewButton.data('payout-data', response.data);
                        var template = wp.template('yith-payouts-modal-view-payout-item');
                            template = $(template(response.data));
                           var header = template.find('.wc-backbone-modal-header');
                           template.remove('.wc-backbone-modal-header');


                        yith.ui.modal(
                            {
                                'width': 500,
                                'title': header,
                                'content': template,
                                'footer': false,
                                'scrollContent': true,
                                'classes': {
                                    content: 'wc-backbone-modal wc-payout-item-preview wc-order-preview',
                                    title: 'yith-payout-item-title',
                                },
                                allowClosingWithEsc: true,
                                closeWhenClickingOnOverlay: true
                            });
                    }
                }
            });
        }
    });
});
