/**
 * HVAC Trainer Profile Admin JavaScript
 * Handles admin functionality for trainer profile management
 *
 * @package HVAC_Community_Events
 * @version 1.0.0
 */

jQuery(document).ready(function($) {
    
    // Test Geocoding Functionality
    $('#test-geocoding').on('click', function(e) {
        e.preventDefault();
        
        const $button = $(this);
        const originalText = $button.text();
        
        // Get test address from user or use default
        const testAddress = prompt('Enter an address to test geocoding:', 'New York, NY, USA');
        if (!testAddress) {
            return;
        }
        
        $button.prop('disabled', true).text('Testing...');
        
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_test_geocoding',
                nonce: hvacProfileAdmin.nonce,
                address: testAddress
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    let message = `Geocoding Test Results:\n\n`;
                    message += `Address: ${data.address}\n`;
                    message += `Coordinates: ${data.coordinates.lat}, ${data.coordinates.lng}\n`;
                    message += `Formatted: ${data.formatted_address}\n`;
                    message += `Confidence: ${data.confidence}`;
                    
                    alert(message);
                } else {
                    alert('Geocoding test failed: ' + response.data);
                }
            },
            error: function() {
                alert('Network error occurred during geocoding test');
            },
            complete: function() {
                $button.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Bulk Geocoding
    let bulkGeocodeRunning = false;
    
    $('#bulk-geocode').on('click', function(e) {
        e.preventDefault();
        
        if (bulkGeocodeRunning) {
            return;
        }
        
        const $button = $(this);
        const originalText = $button.text();
        
        if (!confirm('This will geocode addresses for profiles that don\'t have coordinates yet. Continue?')) {
            return;
        }
        
        bulkGeocodeRunning = true;
        $button.prop('disabled', true).text('Processing...');
        
        performBulkGeocode($button, originalText);
    });
    
    function performBulkGeocode($button, originalText) {
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_bulk_geocode',
                nonce: hvacProfileAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    const processed = response.data.processed;
                    
                    if (processed > 0) {
                        $button.text(`Processed ${processed} profiles...`);
                        
                        // Continue processing if there are more profiles
                        setTimeout(() => {
                            performBulkGeocode($button, originalText);
                        }, 2000);
                    } else {
                        // Finished
                        alert('Bulk geocoding completed!');
                        bulkGeocodeRunning = false;
                        $button.prop('disabled', false).text(originalText);
                        
                        // Refresh the page to update statistics
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    }
                } else {
                    alert('Bulk geocoding failed: ' + response.data);
                    bulkGeocodeRunning = false;
                    $button.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                alert('Network error occurred during bulk geocoding');
                bulkGeocodeRunning = false;
                $button.prop('disabled', false).text(originalText);
            }
        });
    }
    
    // Force Sync All Profiles
    $('#sync-profiles').on('click', function(e) {
        e.preventDefault();
        
        const $button = $(this);
        const originalText = $button.text();
        
        if (!confirm('This will force synchronization between user data and trainer profiles. Continue?')) {
            return;
        }
        
        $button.prop('disabled', true).text('Syncing...');
        
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_sync_profiles',
                nonce: hvacProfileAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('Profile synchronization completed successfully!');
                    
                    // Refresh the page to update statistics
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('Profile synchronization failed: ' + response.data);
                }
            },
            error: function() {
                alert('Network error occurred during profile synchronization');
            },
            complete: function() {
                $button.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // API Key Field Enhancement
    const $apiKeyField = $('input[name="hvac_google_maps_api_key"]');
    if ($apiKeyField.length) {
        // Add show/hide toggle for API key
        const $toggleButton = $('<button type="button" class="button button-secondary" style="margin-left: 10px;">Show</button>');
        
        $apiKeyField.after($toggleButton);
        
        $toggleButton.on('click', function(e) {
            e.preventDefault();
            
            if ($apiKeyField.attr('type') === 'password') {
                $apiKeyField.attr('type', 'text');
                $(this).text('Hide');
            } else {
                $apiKeyField.attr('type', 'password');
                $(this).text('Show');
            }
        });
    }
    
    // Statistics Auto-refresh
    function refreshStatistics() {
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_get_profile_stats',
                nonce: hvacProfileAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    const stats = response.data;
                    
                    // Update statistics display
                    $('.hvac-stat-item').each(function() {
                        const $this = $(this);
                        const $number = $this.find('.hvac-stat-number');
                        const $label = $this.find('.hvac-stat-label');
                        const label = $label.text().toLowerCase();
                        
                        if (label.includes('total')) {
                            $number.text(stats.total_profiles);
                        } else if (label.includes('public')) {
                            $number.text(stats.public_profiles);
                        } else if (label.includes('geocoded')) {
                            $number.text(stats.geocoded_profiles);
                        } else if (label.includes('sync')) {
                            $number.text(stats.sync_issues);
                        }
                    });
                }
            }
        });
    }
    
    // Auto-refresh statistics every 30 seconds
    setInterval(refreshStatistics, 30000);
    
    // Migration Status Check
    function checkMigrationStatus() {
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_get_migration_status',
                nonce: hvacProfileAdmin.nonce
            },
            success: function(response) {
                if (response.success && response.data.status) {
                    const status = response.data;
                    
                    if (status.status === 'in_progress') {
                        showMigrationProgress(status);
                    } else if (status.status === 'not_started') {
                        showMigrationPrompt();
                    }
                }
            }
        });
    }
    
    function showMigrationProgress(status) {
        const message = `Migration in progress... Processed: ${status.processed || 0}/${status.total_records || 0}`;
        
        if (!$('#migration-progress').length) {
            const $progressDiv = $('<div id="migration-progress" class="notice notice-info"><p>' + message + '</p></div>');
            $('.wrap h1').after($progressDiv);
        } else {
            $('#migration-progress p').text(message);
        }
        
        // Check again in 5 seconds
        setTimeout(checkMigrationStatus, 5000);
    }
    
    function showMigrationPrompt() {
        if (!$('#migration-prompt').length && !localStorage.getItem('hvac_migration_dismissed')) {
            const $promptDiv = $(`
                <div id="migration-prompt" class="notice notice-warning is-dismissible">
                    <p><strong>Trainer Profile Migration Available</strong></p>
                    <p>A new trainer profile system is available. Would you like to migrate existing user data to the new system?</p>
                    <p>
                        <button type="button" class="button button-primary" id="start-migration">Start Migration</button>
                        <button type="button" class="button button-secondary" id="dismiss-migration">Dismiss</button>
                    </p>
                </div>
            `);
            
            $('.wrap h1').after($promptDiv);
            
            // Handle migration start
            $('#start-migration').on('click', function() {
                if (confirm('This will migrate existing trainer data to the new profile system. This action cannot be undone. Continue?')) {
                    startMigration();
                }
            });
            
            // Handle dismissal
            $('#dismiss-migration, .notice-dismiss').on('click', function() {
                localStorage.setItem('hvac_migration_dismissed', 'true');
                $('#migration-prompt').remove();
            });
        }
    }
    
    function startMigration() {
        const $button = $('#start-migration');
        $button.prop('disabled', true).text('Starting Migration...');
        
        $.ajax({
            url: hvacProfileAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'hvac_start_migration',
                nonce: hvacProfileAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#migration-prompt').remove();
                    checkMigrationStatus();
                } else {
                    alert('Failed to start migration: ' + response.data);
                    $button.prop('disabled', false).text('Start Migration');
                }
            },
            error: function() {
                alert('Network error occurred while starting migration');
                $button.prop('disabled', false).text('Start Migration');
            }
        });
    }
    
    // Check migration status on page load
    checkMigrationStatus();
    
    // Form validation enhancements
    $('form').on('submit', function(e) {
        const $form = $(this);
        
        // Validate rate limit
        const rateLimit = $form.find('input[name="hvac_geocoding_rate_limit"]').val();
        if (rateLimit && (rateLimit < 1 || rateLimit > 100)) {
            alert('Rate limit must be between 1 and 100 requests per minute');
            e.preventDefault();
            return false;
        }
        
        // Validate API key format (basic check)
        const apiKey = $form.find('input[name="hvac_google_maps_api_key"]').val();
        if (apiKey && apiKey.length < 20) {
            if (!confirm('The API key seems short. Are you sure it\'s correct?')) {
                e.preventDefault();
                return false;
            }
        }
    });
    
    // Advanced settings toggle
    $('.hvac-advanced-settings-toggle').on('click', function(e) {
        e.preventDefault();
        
        const $toggle = $(this);
        const $advanced = $('.hvac-advanced-settings');
        
        if ($advanced.is(':visible')) {
            $advanced.slideUp();
            $toggle.text('Show Advanced Settings');
        } else {
            $advanced.slideDown();
            $toggle.text('Hide Advanced Settings');
        }
    });
    
    // Tooltip functionality for help icons
    $('.hvac-help-icon').on('mouseenter', function() {
        const helpText = $(this).data('help');
        if (helpText) {
            const $tooltip = $('<div class="hvac-tooltip">' + helpText + '</div>');
            $('body').append($tooltip);
            
            const iconPos = $(this).offset();
            $tooltip.css({
                top: iconPos.top - $tooltip.outerHeight() - 10,
                left: iconPos.left - ($tooltip.outerWidth() / 2) + ($(this).outerWidth() / 2)
            });
        }
    }).on('mouseleave', function() {
        $('.hvac-tooltip').remove();
    });
});