(function ($) {

    'use strict';

    /* ===================================
        Load More
    ====================================== */

    $(document).on('click', '#gn-load-more-notifications', function (e) {
        e.preventDefault();

        let _this = $(this);
        let current_page = _this.data('gn-current-page');
        let total_pages = _this.data('gn-total-pages');
        let per_page = _this.data('gn-per-page');
        let ref = _this.data('gn-ref');
        let wrapper = $(document).find('#gn-notifications-wrapper');

        if (current_page >= total_pages) {
            return false;
        }

        _this.addClass('gn-loading').attr('disabled', 'disabled');

        $.ajax({
            url: GigneoCommon.ajax_url,
            type: 'GET',
            data: {
                action: 'gigneo_get_notifications',
                security: GigneoCommon.security,
                paged: current_page + 1,
                per_page: per_page,
                ref: ref,
            },
            success: function (response) {
                _this.removeClass('gn-loading').attr('disabled', false);
                if (response.success && response?.data?.markup?.notification) {

                    //Notification Items
                    let new_wrapper = $(response.data.markup.notification);
                    let items = new_wrapper.find('.gn-notification-item');
                    wrapper.append(items);

                    //Load More
                    let load_more_button = new_wrapper.find('#gn-load-more-notifications').parent();
                    if (load_more_button.length) {
                        _this.parent().html(load_more_button.html());
                    } else {
                        _this.remove();
                    }
                }
            },
            error: function (xhr) {
                _this.removeClass('gn-loading').attr('disabled', false);
                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoCommon.error,
                    text: error_message
                });
            }
        });
    });

    /* ===================================
       Bulk Action
    ====================================== */

    let selected_notifications = [];

    $(document).on('click', '#gn-action-bar-toggler', function (e) {
        e.preventDefault();

        $('#gn-notifications-wrapper').toggleClass('gn-selection-active');
    });

    let notification_actions = $(document).find('#gn-marked-read-notifications, #gn-delete-notifications');

    $(document).on('change', '.gn-notification-item .gn-checkbox input', function (e) {
        selected_notifications = [];

        $('.gn-notification-item .gn-checkbox input:checked').each(function () {
            selected_notifications.push($(this).val());
        });

        if (selected_notifications.length > 0) {
            notification_actions.attr('disabled', false);
        } else {
            notification_actions.attr('disabled', true);
        }

    });

    $(document).on('change', '#gn-select-all-notifications', function () {
        let checked = $(this).is(':checked');
        $('.gn-notification-item .gn-checkbox input').prop('checked', checked).trigger('change');
    });

    $(document).on('click', '#gn-marked-read-notifications', function (e) {
        e.preventDefault();
        let _this = $(this);

        if (selected_notifications.length === 0) {
            return false;
        }

        _this.addClass('gn-loading').attr('disabled', 'disabled');

        $.ajax({
            url: GigneoCommon.ajax_url,
            type: 'POST',
            data: {
                action: 'gigneo_mark_notifications_status',
                security: GigneoCommon.security,
                ids: selected_notifications,
                status: 'read'
            },
            success: function (response) {
                _this.removeClass('gn-loading').attr('disabled', false);
                if (response.success && response?.data?.ids) {
                    let notifications = response?.data?.ids;
                    $.each(notifications, function (key, id) {
                        $(document).find(`#gn-notification-${id}`).removeClass('gn-unread').addClass('gn-read');
                    });
                }
                location.reload();
            },
            error: function (xhr) {
                _this.removeClass('gn-loading').attr('disabled', false);
                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoCommon.error,
                    text: error_message
                });
                location.reload();
            }
        });
    });

    $(document).on('click', '#gn-delete-notifications', function (e) {
        e.preventDefault();
        let proceed = false;

        if (selected_notifications.length === 0) {
            return proceed;
        }

        GigneoAlert.confirm({
            icon: "error",
            text: GigneoCommon.delete_confirmation_desc,
            confirmButtonText: GigneoCommon.delete,
            showLoaderOnConfirm: false,
            allowOutsideClick: () => !Swal.isLoading(),
            preConfirm: () => {
                let confirmBtn = Swal.getConfirmButton();
                confirmBtn.classList.add('gn-loading');
                confirmBtn.disabled = true;

                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: GigneoCommon.ajax_url,
                        method: 'POST',
                        data: {
                            action: 'gigneo_delete_notifications',
                            security: GigneoCommon.security,
                            ids: selected_notifications
                        },
                        success: function (response) {
                            confirmBtn.classList.remove('gn-loading');
                            confirmBtn.disabled = false;
                            if (response.success) {
                                if (response.success && response?.data?.ids) {
                                    let deleted_ids = response.data.ids;

                                    // Remove notifications from DOM
                                    $.each(deleted_ids, function (key, id) {
                                        $(document).find(`#gn-notification-${id}`).remove();
                                    });
                                    let notification_items = $(document).find('.gn-notification-wrapper .gn-notification-item');
                                    if (!notification_items.length) {
                                        location.reload();
                                    }
                                }
                            }
                            resolve();
                            return Promise.resolve();
                        },
                        error: function (xhr) {
                            confirmBtn.classList.remove('gn-loading');
                            confirmBtn.disabled = false;
                            let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: error_message
                            });
                            reject();
                            return Promise.resolve();
                        }
                    });
                });
            }
        });

    });

    $(document).on('click', '.gn-notification-mark-read', function (e) {
        e.preventDefault();
        let _this = $(this);
        let id = _this.attr('data-gn-id');
        let status = _this.attr('data-gn-status');

        _this.addClass('gn-loading').attr('disabled', 'disabled');

        $.ajax({
            url: GigneoCommon.ajax_url,
            type: 'POST',
            data: {
                action: 'gigneo_mark_notifications_status',
                security: GigneoCommon.security,
                ids: [id],
                status: status
            },
            success: function (response) {
                _this.removeClass('gn-loading').attr('disabled', false);
                if (response.success && response?.data?.ids && response?.data?.status) {
                    let notifications = response.data.ids;
                    let status_type = 'read' === response.data.status ? 'unread' : 'read';
                    _this.attr('data-gn-status', status_type);
                    $.each(notifications, function (key, id) {
                        let $notification_list = $(`#gn-notification-${id}`);
                        let $notification_in_line = $(`#gn-notification-in-line-${id}`);

                        if ($notification_list.length) {
                            $notification_list.removeClass('gn-unread gn-read').addClass(`gn-${response.data.status}`);
                        }
                        if ($notification_in_line.length) {
                            $notification_in_line.removeClass('gn-unread gn-read').addClass(`gn-${response.data.status}`);
                        }

                    });
                }
            },
            error: function (xhr) {
                _this.removeClass('gn-loading').attr('disabled', false);
                let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoCommon.error,
                    text: error_message
                });
            }
        });
    });

    $(document).on('click', '.gn-delete-notification', function (e) {
        e.preventDefault();
        let _this = $(this);
        let id = _this.attr('data-gn-id');

        GigneoAlert.confirm({
            icon: "error",
            text: GigneoCommon.delete_confirmation_desc,
            confirmButtonText: GigneoCommon.delete,
            showLoaderOnConfirm: false,
            allowOutsideClick: () => !Swal.isLoading(),
            preConfirm: () => {
                let confirmBtn = Swal.getConfirmButton();
                confirmBtn.classList.add('gn-loading');
                confirmBtn.disabled = true;

                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: GigneoCommon.ajax_url,
                        method: 'POST',
                        data: {
                            action: 'gigneo_delete_notifications',
                            security: GigneoCommon.security,
                            ids: [id]
                        },
                        success: function (response) {
                            confirmBtn.classList.remove('gn-loading');
                            confirmBtn.disabled = false;
                            if (response.success) {
                                if (response.success && response?.data?.ids) {
                                    let deleted_ids = response.data.ids;
                                    $.each(deleted_ids, function (key, id) {
                                        $(document).find(`#gn-notification-${id}`).remove();
                                    });
                                    let notification_items = $(document).find('.gn-notification-wrapper .gn-notification-item');
                                    if (!notification_items.length) {
                                        location.reload();
                                    }
                                }
                            }
                            resolve();
                            return Promise.resolve();
                        },
                        error: function (xhr) {
                            confirmBtn.classList.remove('gn-loading');
                            confirmBtn.disabled = false;
                            let error_message = xhr?.responseJSON?.data?.message || GigneoCommon.went_wrong;
                            GigneoAlert.toast({
                                icon: 'error',
                                title: GigneoCommon.error,
                                text: error_message
                            });
                            reject();
                            return Promise.resolve();
                        }
                    });
                });
            }
        });


    });

}(jQuery));