class UsersDashbord {

    _current_page = 1;
    _per_page = 20;

    init() {
        if (!jQuery('#users-dashboard-ui')[0]) {
            return;
        }
        this._handleEvents();

        // Load initial data
        this._refresh();
    }

    _handleEvents() {
        const _this = this;

        jQuery(document).on('click', '.users_pagination_prev', function(event) {
            event.preventDefault();
            if (_this._current_page > 1) {
                _this._current_page--;
                _this._refresh();
            }
        });

        jQuery(document).on('click', '.users_pagination_next', function(event) {
            event.preventDefault();
            _this._current_page++;
            _this._refresh();
        });

        jQuery('.users_per_page').on('change', function(event) {
            _this._per_page = parseInt(this.value);
            _this._current_page = 1; // Reset to first page
            _this._refresh();
        });

        jQuery(document).on('change', '.user-field-dropdown', function(event) {
            const userId = jQuery(this).data('user-id');
            const field = jQuery(this).data('field');
            const value = jQuery(this).val();
            const dropdown = jQuery(this);

            dropdown.prop('disabled', true);

            _this._updateUserField(userId, field, value, dropdown);
        });

        jQuery(document).on('click', '.user-delete-btn', function(event) {
            event.preventDefault();
            const userId = jQuery(this).data('user-id');
            const userEmail = jQuery(this).data('user-email');
            const button = jQuery(this);

            const confirmMessageTemplate = window.OXYLEAF_ADMIN_SETTINGS?.labels?.delete_user_confirm || 'Are you sure you want to delete user "%s"? This action cannot be undone.';
            const confirmMessage = confirmMessageTemplate.replace('%s', userEmail);

            if (confirm(confirmMessage)) {
                button.prop('disabled', true);
                button.text('Deleting...');
                _this._deleteUser(userId, button);
            }
        });
    }

    _refresh() {
        const ajaxPayload = {
            action: 'oxygen_app_search_users',
            nonce: window.OXYLEAF_APP_AJAX?.nonce || '',
            params: {
                page: this._current_page,
                per_page: this._per_page,
            }
        };

        this._showPreloader();

        const _this = this;
        jQuery.ajax({
            url: window.OXYLEAF_APP_AJAX?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                _this._hidePreloader();

                if (response.success) {
                    _this._updateTable(response.data.data);
                    _this._updatePagination(response.data.pagination);
                } else {
                    _this._showNoUsers();
                }
            },
            error: function(xhr, status, error) {
                _this._hidePreloader();
                console.error('Ajax Error:', error);
                _this._showNoUsers();
            }
        });

        return ajaxPayload;
    }

    _showPreloader() {
        jQuery('.main_preloader').show();
        jQuery('.users_table').hide();
        jQuery('.no_users').hide();
        jQuery('.users_pagination').hide();
    }

    _hidePreloader() {
        jQuery('.main_preloader').hide();
    }

    _updateTable(users) {
        const tbody = jQuery('.users_tbody');
        tbody.empty();

        if (!users || users.length === 0) {
            this._showNoUsers();
            return;
        }

        jQuery('.users_table').show();
        jQuery('.no_users').hide();

        users.forEach(user => {
            const row = this._buildTableRow(user);
            tbody.append(row);
        });
    }

    _buildTableRow(user) {
        const isActive = parseInt(user.is_active) === 1 ?
            '<span class="badge bg-success">Yes</span>' :
            '<span class="badge bg-secondary">No</span>';

        const createdDate = user.creation_date ?
            new Date(user.creation_date).toLocaleString() :
            '-';

        const lastLogin = user.last_login_time ?
            new Date(user.last_login_time).toLocaleString() :
            '-';

        const name = user.name || '-';

        const deleteButton = `
            <button class="btn btn-sm btn-danger user-delete-btn" data-user-id="${user.id}" data-user-email="${user.email}">
                Delete
            </button>
        `;

        return `
            <tr>
                <td>${user.id}</td>
                <td><strong>${user.email}</strong></td>
                <td>${name}</td>
                <td>${isActive}</td>
                <td>${createdDate}</td>
                <td>${lastLogin}</td>
                <td>${deleteButton}</td>
            </tr>
        `;
    }

    _showNoUsers() {
        jQuery('.users_table').hide();
        jQuery('.no_users').show();
        jQuery('.users_pagination').hide();
    }

    _updatePagination(pagination) {
        if (!pagination) {
            jQuery('.users_pagination').hide();
            return;
        }

        const { current_page, per_page, total_results, total_pages, has_prev, has_next } = pagination;

        const startResult = total_results === 0 ? 0 : ((current_page - 1) * per_page) + 1;
        const endResult = Math.min(current_page * per_page, total_results);

        const paginationText = `Showing ${startResult}-${endResult} of ${total_results} users`;
        jQuery('.users_pagination .pagination_text').text(paginationText);

        const prevBtn = jQuery('.users_pagination_prev');
        const nextBtn = jQuery('.users_pagination_next');

        if (has_prev) {
            prevBtn.removeClass('disabled').css('opacity', '1');
        } else {
            prevBtn.addClass('disabled').css('opacity', '0.5');
        }

        if (has_next) {
            nextBtn.removeClass('disabled').css('opacity', '1');
        } else {
            nextBtn.addClass('disabled').css('opacity', '0.5');
        }

        jQuery('.users_pagination').show();
    }

    _updateUserField(userId, field, value, dropdown) {
        const _this = this;

        const ajaxPayload = {
            action: 'oxygen_app_update_user_field',
            nonce: window.OXYLEAF_APP_AJAX?.nonce || '',
            user_id: userId,
            field: field,
            value: value
        };

        jQuery.ajax({
            url: window.OXYLEAF_APP_AJAX?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                dropdown.prop('disabled', false);

                if (response.success) {
                    // Successfully updated field
                    // _this._refresh();
                } else {
                    console.error(response.data?.message || 'Failed to update user');
                    dropdown.val(value === '1' ? '0' : '1');
                }
            },
            error: function(xhr, status, error) {
                dropdown.prop('disabled', false);
                console.error('Ajax Error:', error);
                dropdown.val(value === '1' ? '0' : '1');
            }
        });
    }

    _deleteUser(userId, button) {
        const _this = this;

        const ajaxPayload = {
            action: 'oxygen_app_delete_user',
            nonce: window.OXYLEAF_APP_AJAX?.nonce || '',
            user_id: userId
        };

        jQuery.ajax({
            url: window.OXYLEAF_APP_AJAX?.ajax_url || ajaxurl,
            type: 'POST',
            data: ajaxPayload,
            success: function(response) {
                if (response.success) {
                    // Remove the row from the table with animation
                    button.closest('tr').fadeOut(300, function() {
                        jQuery(this).remove();
                        // Refresh the table to update pagination
                        _this._refresh();
                    });
                } else {
                    button.prop('disabled', false);
                    button.text('Delete');
                    alert(response.data?.message || 'Failed to delete user');
                }
            },
            error: function(xhr, status, error) {
                button.prop('disabled', false);
                button.text('Delete');
                console.error('Ajax Error:', error);
                alert('An error occurred while deleting the user. Please try again.');
            }
        });
    }

    getAjaxPayload() {
        return this._refresh();
    }
}

export default UsersDashbord;