jQuery(document).ready(function($) {
    'use strict';
    
    // Refresh metrics
    $('#refresh-metrics').on('click', function() {
        var $button = $(this);
        $button.prop('disabled', true).text('Refreshing...');
        
        $.ajax({
            url: hvac_admin_dashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_refresh_dashboard_metrics',
                nonce: hvac_admin_dashboard.nonce
            },
            success: function(response) {
                if (response.success) {
                    updateMetrics(response.data);
                    showNotice('Metrics refreshed successfully', 'success');
                } else {
                    showNotice('Failed to refresh metrics', 'error');
                }
            },
            error: function() {
                showNotice('Error refreshing metrics', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text('Refresh All Metrics');
            }
        });
    });
    
    // Export metrics
    $('#export-metrics').on('click', function() {
        var $button = $(this);
        $button.prop('disabled', true).text('Exporting...');
        
        $.ajax({
            url: hvac_admin_dashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_export_metrics',
                nonce: hvac_admin_dashboard.nonce
            },
            success: function(response) {
                if (response.success) {
                    downloadCSV(response.data.csv, response.data.filename);
                    showNotice('Metrics exported successfully', 'success');
                } else {
                    showNotice('Failed to export metrics', 'error');
                }
            },
            error: function() {
                showNotice('Error exporting metrics', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text('Export Metrics (CSV)');
            }
        });
    });
    
    // Maintenance actions
    $('.maintenance-actions button').on('click', function() {
        var $button = $(this);
        var action = $button.data('action');
        
        if (!confirm('Are you sure you want to run this maintenance action?')) {
            return;
        }
        
        $button.prop('disabled', true).text('Running...');
        $('.maintenance-log').show();
        $('#maintenance-output').text('Running ' + action + '...');
        
        $.ajax({
            url: hvac_admin_dashboard.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_run_maintenance',
                action_type: action,
                nonce: hvac_admin_dashboard.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#maintenance-output').append('\n' + response.data.message);
                    showNotice('Maintenance action completed', 'success');
                } else {
                    $('#maintenance-output').append('\nError: ' + response.data.message);
                    showNotice('Maintenance action failed', 'error');
                }
            },
            error: function() {
                $('#maintenance-output').append('\nError: Failed to run maintenance action');
                showNotice('Error running maintenance action', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text($button.text().replace('Running...', ''));
            }
        });
    });
    
    // Update metrics on the page
    function updateMetrics(data) {
        // Update trainer metrics
        if (data.trainer) {
            updateMetricValue('.hvac-dashboard-widget:contains("Trainer Metrics")', 'Total Trainers', data.trainer.total_trainers);
            updateMetricValue('.hvac-dashboard-widget:contains("Trainer Metrics")', 'New This Week', data.trainer.new_trainers_week);
            updateMetricValue('.hvac-dashboard-widget:contains("Trainer Metrics")', 'Total Logins', data.trainer.total_logins);
            updateMetricValue('.hvac-dashboard-widget:contains("Trainer Metrics")', 'Logins This Week', data.trainer.logins_week);
        }
        
        // Update event statistics
        if (data.events) {
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Total Events', data.events.total_events);
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Past Events', data.events.past_events);
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Future Events', data.events.future_events);
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Draft Events', data.events.draft_events);
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Cancelled Events', data.events.cancelled_events);
            updateMetricValue('.hvac-dashboard-widget:contains("Event Statistics")', 'Total Attendees', data.events.total_attendees);
        }
        
        // Update revenue statistics
        if (data.revenue) {
            updateMetricValue('.hvac-dashboard-widget:contains("Revenue Statistics")', 'Total Revenue', '$' + formatNumber(data.revenue.total_revenue));
            updateMetricValue('.hvac-dashboard-widget:contains("Revenue Statistics")', 'Revenue This Week', '$' + formatNumber(data.revenue.revenue_week));
            updateMetricValue('.hvac-dashboard-widget:contains("Revenue Statistics")', 'Total Purchases', data.revenue.total_purchases);
            updateMetricValue('.hvac-dashboard-widget:contains("Revenue Statistics")', 'Purchases This Week', data.revenue.purchases_week);
        }
    }
    
    // Update individual metric value
    function updateMetricValue(widgetSelector, metricLabel, newValue) {
        $(widgetSelector).find('.metric').each(function() {
            if ($(this).find('.metric-label').text() === metricLabel) {
                $(this).find('.metric-value').text(newValue);
                // Add animation
                $(this).find('.metric-value').addClass('updated');
                setTimeout(function() {
                    $(this).find('.metric-value').removeClass('updated');
                }.bind(this), 1000);
            }
        });
    }
    
    // Format number with commas
    function formatNumber(num) {
        return parseFloat(num).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    // Download CSV
    function downloadCSV(csvData, filename) {
        var csv = csvData.map(function(row) {
            return row.map(function(cell) {
                // Escape quotes and wrap in quotes if contains comma
                if (typeof cell === 'string' && (cell.includes(',') || cell.includes('"'))) {
                    return '"' + cell.replace(/"/g, '""') + '"';
                }
                return cell;
            }).join(',');
        }).join('\n');
        
        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        
        if (link.download !== undefined) {
            var url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
    
    // Show notice
    function showNotice(message, type) {
        var $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');
        $('.wrap').prepend($notice);
        
        // Auto-dismiss after 5 seconds
        setTimeout(function() {
            $notice.fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
    }
    
    // Auto-refresh metrics every 5 minutes
    setInterval(function() {
        $('#refresh-metrics').trigger('click');
    }, 300000);
});