/**
 * HVAC Trainer Dashboard Enhanced JavaScript
 * 
 * Handles dynamic filtering, sorting, pagination, and search for the events table.
 */
(function($) {
    'use strict';

    // Store current state
    let currentState = {
        status: 'all',
        search: '',
        orderby: 'date',
        order: 'DESC',
        page: 1,
        per_page: 10,
        date_from: '',
        date_to: ''
    };

    // Debounce timer for search
    let searchTimer = null;

    // Initialize the dashboard when DOM is ready
    $(document).ready(function() {
        initializeEnhancedDashboard();
    });

    /**
     * Initialize all enhanced dashboard features
     */
    function initializeEnhancedDashboard() {
        // Initialize state from URL params
        initializeStateFromURL();
        
        // Set up event handlers
        initEventFilters();
        initSearchBox();
        initDateFilters();
        initPerPageSelector();
        initSortableColumns();
        initPagination();
    }

    /**
     * Initialize state from URL parameters
     */
    function initializeStateFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        
        currentState.status = urlParams.get('event_status') || 'all';
        currentState.search = urlParams.get('search') || '';
        currentState.orderby = urlParams.get('orderby') || 'date';
        currentState.order = urlParams.get('order') || 'DESC';
        currentState.page = parseInt(urlParams.get('paged')) || 1;
        currentState.per_page = parseInt(urlParams.get('per_page')) || 10;
        currentState.date_from = urlParams.get('date_from') || '';
        currentState.date_to = urlParams.get('date_to') || '';
        
        // Update UI elements to match state
        $('#hvac-event-search').val(currentState.search);
        $('#hvac-date-from').val(currentState.date_from);
        $('#hvac-date-to').val(currentState.date_to);
        $('#hvac-per-page').val(currentState.per_page);
    }

    /**
     * Initialize status filter tabs
     */
    function initEventFilters() {
        $('.hvac-event-filters a').on('click', function(e) {
            e.preventDefault();
            
            const status = $(this).data('status');
            currentState.status = status;
            currentState.page = 1; // Reset to first page when filtering
            
            // Update active class
            $('.hvac-event-filters a').removeClass('hvac-filter-active ast-button-primary').addClass('ast-button-secondary');
            $(this).addClass('hvac-filter-active ast-button-primary').removeClass('ast-button-secondary');
            
            // Refresh table
            refreshEventsTable();
        });
    }

    /**
     * Initialize search box
     */
    function initSearchBox() {
        $('#hvac-event-search').on('keyup', function() {
            const searchTerm = $(this).val();
            
            // Clear existing timer
            if (searchTimer) {
                clearTimeout(searchTimer);
            }
            
            // Set new timer to debounce search
            searchTimer = setTimeout(function() {
                currentState.search = searchTerm;
                currentState.page = 1; // Reset to first page when searching
                refreshEventsTable();
            }, 500); // 500ms delay
        });
    }

    /**
     * Initialize date filters
     */
    function initDateFilters() {
        $('#hvac-date-from, #hvac-date-to').on('change', function() {
            currentState.date_from = $('#hvac-date-from').val();
            currentState.date_to = $('#hvac-date-to').val();
            currentState.page = 1; // Reset to first page when filtering
            refreshEventsTable();
        });
    }

    /**
     * Initialize per page selector
     */
    function initPerPageSelector() {
        $('#hvac-per-page').on('change', function() {
            currentState.per_page = parseInt($(this).val());
            currentState.page = 1; // Reset to first page when changing per page
            refreshEventsTable();
        });
    }

    /**
     * Initialize sortable column headers
     */
    function initSortableColumns() {
        $(document).on('click', '.hvac-events-table-wrapper th.sortable a', function(e) {
            e.preventDefault();
            
            const orderby = $(this).data('orderby');
            const order = $(this).data('order');
            
            currentState.orderby = orderby;
            currentState.order = order;
            currentState.page = 1; // Reset to first page when sorting
            
            refreshEventsTable();
        });
    }

    /**
     * Initialize pagination controls
     */
    function initPagination() {
        // Pagination links
        $(document).on('click', '.pagination-links a:not(.disabled)', function(e) {
            e.preventDefault();
            
            const page = parseInt($(this).data('page'));
            if (page) {
                currentState.page = page;
                refreshEventsTable();
            }
        });
        
        // Page input field
        $(document).on('keypress', '.current-page', function(e) {
            if (e.which === 13) { // Enter key
                e.preventDefault();
                const page = parseInt($(this).val());
                const totalPages = parseInt($('.total-pages').text());
                
                if (page >= 1 && page <= totalPages) {
                    currentState.page = page;
                    refreshEventsTable();
                }
            }
        });
    }

    /**
     * Refresh the events table via AJAX
     */
    function refreshEventsTable() {
        const $eventsTableWrapper = $('.hvac-events-table-wrapper');
        
        // Show loading indicator
        $eventsTableWrapper.addClass('loading').append('<div class="hvac-loading">Loading events...</div>');
        
        // Make AJAX request
        $.ajax({
            url: hvac_dashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_filter_events',
                status: currentState.status,
                search: currentState.search,
                orderby: currentState.orderby,
                order: currentState.order,
                page: currentState.page,
                per_page: currentState.per_page,
                date_from: currentState.date_from,
                date_to: currentState.date_to,
                nonce: hvac_dashboard.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Replace the table HTML
                    $eventsTableWrapper.html(response.data.html);
                    
                    // Update URL without reloading the page
                    updateURL();
                    
                    // Scroll to top of table
                    $('html, body').animate({
                        scrollTop: $('.hvac-dashboard-events').offset().top - 50
                    }, 300);
                } else {
                    showError('Error loading events: ' + response.data.message);
                }
            },
            error: function() {
                showError('Error communicating with server.');
            },
            complete: function() {
                $eventsTableWrapper.removeClass('loading');
            }
        });
    }

    /**
     * Update URL parameters without reloading
     */
    function updateURL() {
        if (!history.pushState) return;
        
        const params = new URLSearchParams();
        
        // Only add non-default values to URL
        if (currentState.status !== 'all') params.set('event_status', currentState.status);
        if (currentState.search) params.set('search', currentState.search);
        if (currentState.orderby !== 'date') params.set('orderby', currentState.orderby);
        if (currentState.order !== 'DESC') params.set('order', currentState.order);
        if (currentState.page > 1) params.set('paged', currentState.page);
        if (currentState.per_page !== 10) params.set('per_page', currentState.per_page);
        if (currentState.date_from) params.set('date_from', currentState.date_from);
        if (currentState.date_to) params.set('date_to', currentState.date_to);
        
        const newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
        window.history.pushState({ path: newUrl }, '', newUrl);
    }

    /**
     * Show error message
     */
    function showError(message) {
        $('.hvac-events-table-wrapper')
            .html('<div class="hvac-error notice notice-error"><p>' + message + '</p></div>');
    }

})(jQuery);