jQuery(document).ready(function($) {
    var migrationSteps = [
        'settings',
        'clients',
        'post_types',
        'meta',
        'pro_options',
        'cleanup'
    ];

    var stepLabels = {
        'settings': 'Settings',
        'clients': 'Clients',
        'post_types': 'Posts',
        'meta': 'Meta Data',
        'pro_options': 'Pro Options',
        'cleanup': 'Cleanup'
    };

    var currentStep = 0;
    var migrationRunning = false;
    var migrationLogs = [];

    function updateProgress(step, status, message) {
        var $step = $('#migration-step-' + step);
        $step.removeClass('pending running success error')
             .addClass(status);
        
        if (message) {
            $step.find('.step-message').text(message);
        }

        // Update progress bar
        var progress = ((currentStep + 1) / migrationSteps.length) * 100;
        $('#migration-progress').css('width', progress + '%');
    }

    function appendLog(message, level) {
        var $log = $('#migration-log');
        var timestamp = new Date().toLocaleTimeString();
        var levelClass = level === 'error' ? 'text-danger' : 
                        level === 'success' ? 'text-success' : 'text-info';
        var logEntry = '[' + timestamp + '] ' + message + '\n';
        
        // Store log for copying
        migrationLogs.push(logEntry);
        
        $log.append('<div class="log-entry ' + levelClass + '">' +
            '<span class="log-time">[' + timestamp + ']</span> ' +
            '<span class="log-message">' + message + '</span>' +
            '</div>'
        );
        
        // Auto-scroll to bottom
        $log.scrollTop($log[0].scrollHeight);
    }

    function showError(message) {
        $('#migration-error').html(message).show();
        appendLog(message, 'error');
    }

    function runMigrationStep() {
        if (currentStep >= migrationSteps.length) {
            migrationRunning = false;
            $('#start-migration').prop('disabled', false).text('Migration Complete');
            appendLog('Migration completed successfully', 'success');
                return;
            }
            
        var step = migrationSteps[currentStep];
        updateProgress(step, 'running', 'Running...');
        appendLog('Starting ' + stepLabels[step] + ' migration...', 'info');

            $.ajax({
                url: easyInvoiceMigration.ajaxurl,
                type: 'POST',
                data: {
                action: 'easy_invoice_migration',
                nonce: easyInvoiceMigration.nonce,
                step: step
                },
                success: function(response) {
                    if (response.success) {
                    var result = response.data;
                    
                    // Add logs
                    if (result.log) {
                        result.log.forEach(function(entry) {
                            appendLog(entry.message, entry.level);
                        });
                    }

                    if (result.success) {
                        updateProgress(step, 'success', result.message);
                        currentStep++;
                        runMigrationStep();
                    } else {
                        updateProgress(step, 'error', result.message);
                        showError(stepLabels[step] + ' migration failed: ' + result.message);
                        migrationRunning = false;
                        $('#start-migration').prop('disabled', false).text('Retry Migration');
                    }
                } else {
                    updateProgress(step, 'error', response.data.message);
                    showError(stepLabels[step] + ' migration failed: ' + response.data.message);
                    migrationRunning = false;
                    $('#start-migration').prop('disabled', false).text('Retry Migration');
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = error;
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {}
                
                updateProgress(step, 'error', 'AJAX error: ' + errorMessage);
                showError(stepLabels[step] + ' migration failed: ' + errorMessage);
                migrationRunning = false;
                $('#start-migration').prop('disabled', false).text('Retry Migration');
                
                // Log the full error details
                console.error('Migration AJAX error:', {
                    status: status,
                    error: error,
                    xhr: xhr
                });
            }
        });
    }

    $('#start-migration').click(function(e) {
        e.preventDefault();

        if (migrationRunning) {
            return;
        }

        // Reset UI
        migrationRunning = true;
        currentStep = 0;
        migrationLogs = [];
        $('#migration-error').hide();
        $('#migration-log').empty();
        $('.migration-step').removeClass('success error').addClass('pending');
        $(this).prop('disabled', true).text('Migration Running...');

        // Get migration counts first
            $.ajax({
                url: easyInvoiceMigration.ajaxurl,
            type: 'GET',
                data: {
                action: 'easy_invoice_migration_counts',
                    nonce: easyInvoiceMigration.nonce
                },
                success: function(response) {
                    if (response.success) {
                    var counts = response.data;
                    appendLog('Found items to migrate:', 'info');
                    appendLog('- Invoices: ' + counts.invoices, 'info');
                    appendLog('- Quotes: ' + counts.quotes, 'info');
                    appendLog('- Payments: ' + counts.payments, 'info');
                    appendLog('- Settings: ' + counts.options, 'info');
                    
                    // Show detailed counts if available
                    if (counts.details) {
                        appendLog('\nDetailed counts:', 'info');
                        appendLog('- Invoice meta entries: ' + counts.details.invoice_meta_count, 'info');
                        appendLog('- Quote meta entries: ' + counts.details.quote_meta_count, 'info');
                        appendLog('- Payment meta entries: ' + counts.details.payment_meta_count, 'info');
                    }
                    
                    runMigrationStep();
                } else {
                    showError('Failed to get migration counts: ' + (response.data ? response.data.message : 'Unknown error'));
                    migrationRunning = false;
                    $('#start-migration').prop('disabled', false).text('Start Migration');
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = error;
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    }
                } catch (e) {}
                
                showError('Failed to get migration counts: ' + errorMessage);
                migrationRunning = false;
                $('#start-migration').prop('disabled', false).text('Start Migration');
                
                // Log the full error details
                console.error('Migration counts AJAX error:', {
                    status: status,
                    error: error,
                    xhr: xhr
                });
            }
        });
    });

    // Copy log functionality
    $('#copy-log').click(function() {
        var $button = $(this);
        var logText = migrationLogs.join('');
        
        // Create temporary textarea
        var $temp = $('<textarea>');
        $('body').append($temp);
        $temp.val(logText).select();
        
        try {
            // Copy text
            document.execCommand('copy');
            
            // Update button text
            $button.addClass('copied').html('<span class="dashicons dashicons-yes"></span> Copied!');
            
            // Reset button after 2 seconds
            setTimeout(function() {
                $button.removeClass('copied').html('<span class="dashicons dashicons-clipboard"></span> Copy Log');
            }, 2000);
        } catch (err) {
            console.error('Failed to copy log:', err);
        }
        
        // Remove temporary textarea
        $temp.remove();
    });
});