document.addEventListener('DOMContentLoaded', function() {
    // Export form handling
    const exportForm = document.getElementById('exportForm');
    const exportBtn = document.getElementById('exportBtn');
    const selectAllBtn = document.getElementById('selectAll');
    const selectNoneBtn = document.getElementById('selectNone');
    
    // Import form handling
    const importForm = document.getElementById('importForm');
    const importBtn = document.getElementById('importBtn');
    const progressBar = document.getElementById('progressBar');
    const importLog = document.getElementById('importLog');
    const logContent = document.getElementById('logContent');
    const fileInput = document.getElementById('import_file');
    
    // Export functionality
    if (exportForm) {
        // Select all/none buttons
        if (selectAllBtn) {
            selectAllBtn.addEventListener('click', function() {
                const checkboxes = document.querySelectorAll('input[name="tables[]"]');
                checkboxes.forEach(cb => cb.checked = true);
            });
        }
        
        if (selectNoneBtn) {
            selectNoneBtn.addEventListener('click', function() {
                const checkboxes = document.querySelectorAll('input[name="tables[]"]');
                checkboxes.forEach(cb => cb.checked = false);
            });
        }
        
        // Export form submission
        exportForm.addEventListener('submit', function(e) {
            const checkedTables = document.querySelectorAll('input[name="tables[]"]:checked');
            
            if (checkedTables.length === 0) {
                e.preventDefault();
                alert('Please select at least one table to export.');
                return false;
            }
            
            // Show loading state
            if (exportBtn) {
                exportBtn.disabled = true;
                exportBtn.innerHTML = '<span class="loading"></span> Exporting...';
                
                // Re-enable button after 5 seconds (in case download doesn't start)
                setTimeout(() => {
                    exportBtn.disabled = false;
                    exportBtn.innerHTML = '<i class="fas fa-download"></i> Export Now';
                }, 5000);
            }
        });
    }
    
    // Import functionality
    if (importForm) {
        // File input validation
        if (fileInput) {
            fileInput.addEventListener('change', function() {
                const file = this.files[0];
                if (file) {
                    const maxSize = 50 * 1024 * 1024; // 50MB
                    const allowedTypes = ['application/sql', 'text/plain', 'application/octet-stream'];
                    
                    // Size validation
                    if (file.size > maxSize) {
                        alert('File size exceeds 50MB limit. Please choose a smaller file.');
                        this.value = '';
                        return;
                    }
                    
                    // Type validation
                    if (!allowedTypes.includes(file.type) && !file.name.toLowerCase().endsWith('.sql')) {
                        alert('Please select a valid SQL file.');
                        this.value = '';
                        return;
                    }
                    
                    // Show file info
                    showFileInfo(file);
                }
            });
        }
        
        // Import form submission
        importForm.addEventListener('submit', function(e) {
            const fileInput = document.getElementById('import_file');
            const backupConfirm = document.getElementById('backup_confirm');
            
            // Validate file selection
            if (!fileInput.files.length) {
                e.preventDefault();
                alert('Please select a SQL file to import.');
                return false;
            }
            
            // Validate backup confirmation
            if (!backupConfirm.checked) {
                e.preventDefault();
                alert('Please confirm that you have created a backup.');
                return false;
            }
            
            // Show confirmation dialog
            if (!confirm('Are you sure you want to proceed with the import? This action cannot be undone.')) {
                e.preventDefault();
                return false;
            }
            
            // Show progress and disable button
            showImportProgress();
        });
    }
    
    // Utility functions
    function showFileInfo(file) {
        const fileSize = formatBytes(file.size);
        const fileName = file.name;
        
        // Remove existing file info
        const existingInfo = document.querySelector('.file-info');
        if (existingInfo) {
            existingInfo.remove();
        }
        
        // Create file info element
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        fileInfo.innerHTML = `
            <strong>Selected file:</strong> ${fileName}<br>
            <strong>Size:</strong> ${fileSize}<br>
            <strong>Type:</strong> ${file.type || 'Unknown'}
        `;
        
        // Insert after file input
        fileInput.parentNode.insertBefore(fileInfo, fileInput.nextSibling);
    }
    
    function showImportProgress() {
        if (importBtn) {
            importBtn.disabled = true;
            importBtn.innerHTML = '<span class="loading"></span> Importing...';
        }
        
        if (progressBar) {
            progressBar.style.display = 'block';
            const progressBarInner = progressBar.querySelector('.progress-bar');
            progressBarInner.style.width = '10%';
            progressBarInner.classList.add('progress-bar-animated', 'progress-bar-striped');
        }
        
        if (importLog) {
            importLog.style.display = 'block';
            if (logContent) {
                logContent.textContent = 'Starting import process...\n';
            }
        }
        
        // Simulate progress (you can replace this with actual progress tracking)
        simulateProgress();
    }
    
    function simulateProgress() {
        let progress = 10;
        const progressBarInner = document.querySelector('.progress-bar');
        
        const interval = setInterval(() => {
            progress += Math.random() * 20;
            if (progress > 90) {
                progress = 90;
            }
            
            if (progressBarInner) {
                progressBarInner.style.width = progress + '%';
            }
            
            if (logContent) {
                logContent.textContent += `Processing... ${Math.round(progress)}%\n`;
                logContent.scrollTop = logContent.scrollHeight;
            }
            
            if (progress >= 90) {
                clearInterval(interval);
            }
        }, 500);
    }
    
    function formatBytes(bytes, decimals = 2) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }
    
    // Auto-refresh statistics every 30 seconds on dashboard
    if (window.location.href.includes('view=exportimport')) {
        setInterval(function() {
            // You can implement AJAX refresh here if needed
            console.log('Auto-refresh statistics');
        }, 30000);
    }
    
    // Confirmation dialogs for dangerous operations
    document.querySelectorAll('[data-confirm]').forEach(element => {
        element.addEventListener('click', function(e) {
            const message = this.getAttribute('data-confirm');
            if (!confirm(message)) {
                e.preventDefault();
            }
        });
    });
    
    // Tooltip initialization (if using Bootstrap tooltips)
    if (typeof bootstrap !== 'undefined') {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }
    
    // Show notifications
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 5000);
    }
    
    // Handle AJAX responses (if you implement AJAX functionality)
    function handleAjaxResponse(response) {
        try {
            const data = JSON.parse(response);
            if (data.success) {
                showNotification(data.message, 'success');
            } else {
                showNotification(data.message, 'error');
            }
        } catch (e) {
            showNotification('An error occurred while processing the request.', 'error');
        }
    }
});
