package components

import (
    "context"
    "time"
)

// BackupFile represents a database backup file
type BackupFile struct {
    Name     string
    Size     string
    Created  time.Time
    FullPath string
}

// AdminDatabaseTools renders the database tools page with backup and restore functionality
templ AdminDatabaseTools(ctx context.Context, backups []BackupFile) {
    @LayoutWithContext("Database Tools", ctx) {
        <div id="database-tools-container" style="min-height: 100vh;" class="database-tools-page bg-gray-50 dark:bg-gray-900">
            <div class="pb-8 w-full">
                <!-- Page Header -->
                <div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <h1 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center">
                        <i class="fas fa-database w-6 h-6 mr-2 text-blue-500 dark:text-blue-400"></i>
                        Database Tools
                    </h1>
                    <form id="backup-form" method="POST" action="/admin/database/backup-database">
                        <button type="submit" class="flex items-center justify-center text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">
                            <i class="fas fa-download w-4 h-4 mr-2"></i>
                            Create Backup
                        </button>
                    </form>
                </div>

                <!-- Status and Error Messages -->
                <div id="toast-container" class="fixed top-5 right-5 z-50 flex flex-col gap-2"></div>

                <!-- Action Cards Grid -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                    <!-- Optimize Database Card -->
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-6 dark:bg-gray-800 dark:border-gray-700">
                        <div class="flex items-center mb-4">
                            <div class="bg-purple-100 p-3 rounded-full dark:bg-purple-900 mr-4">
                                <i class="fas fa-broom text-purple-500 w-6 h-6 dark:text-purple-300"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Optimize Database</h3>
                        </div>
                        <p class="text-gray-600 dark:text-gray-400 mb-4">Vacuum the database to reclaim space and optimize performance.</p>
                        <form id="vacuum-form" method="POST" action="/admin/database/vacuum-database">
                            <button type="submit" class="w-full px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-purple-700 dark:hover:bg-purple-800">
                                <i class="fas fa-magic mr-2"></i>
                                Optimize Database
                            </button>
                        </form>
                    </div>

                    <!-- Clear Job History Card -->
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-6 dark:bg-gray-800 dark:border-gray-700">
                        <div class="flex items-center mb-4">
                            <div class="bg-orange-100 p-3 rounded-full dark:bg-orange-900 mr-4">
                                <i class="fas fa-eraser text-orange-500 w-6 h-6 dark:text-orange-300"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Clear Job History</h3>
                        </div>
                        <p class="text-gray-600 dark:text-gray-400 mb-4">Remove old job history records to free up database space.</p>
                        <form id="clear-job-form" method="POST" action="/admin/database/clear-job-history">
                            <button type="submit" class="w-full px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-500 dark:bg-orange-700 dark:hover:bg-orange-800">
                                <i class="fas fa-trash-alt mr-2"></i>
                                Clear Job History
                            </button>
                        </form>
                    </div>

                    <!-- Export Configuration Card -->
                    <div class="bg-white border border-gray-200 rounded-lg shadow-sm p-6 dark:bg-gray-800 dark:border-gray-700">
                        <div class="flex items-center mb-4">
                            <div class="bg-green-100 p-3 rounded-full dark:bg-green-900 mr-4">
                                <i class="fas fa-file-export text-green-500 w-6 h-6 dark:text-green-300"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Export Configuration</h3>
                        </div>
                        <p class="text-gray-600 dark:text-gray-400 mb-4">Export system configurations and jobs for backup or migration.</p>
                        <div class="flex space-x-2">
                            <a href="/admin/database/export-configs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
                                <i class="fas fa-cogs mr-2"></i>
                                Export Configs
                            </a>
                            <a href="/admin/database/export-jobs" class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-green-700 dark:hover:bg-green-800 text-center">
                                <i class="fas fa-tasks mr-2"></i>
                                Export Jobs
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Database Backup List -->
                <div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800">
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Database Backups</h3>
                        <a href="/admin/database/refresh-backups" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                            <i class="fas fa-sync-alt mr-1"></i>
                            Refresh
                        </a>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50 dark:bg-gray-700">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Backup Name</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Size</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Created</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                                if len(backups) == 0 {
                                    <tr>
                                        <td colspan="4" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                                            No backups found. Create your first backup to get started.
                                        </td>
                                    </tr>
                                } else {
                                    for _, backup := range backups {
                                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td class="px-6 py-4 text-sm text-gray-900 dark:text-white">{ backup.Name }</td>
                                            <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">{ backup.Size }</td>
                                            <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">{ backup.Created.Format("2006-01-02 15:04:05") }</td>
                                            <td class="px-6 py-4 text-sm text-right">
                                                <div class="flex items-center justify-end space-x-2">
                                                    <button type="button" 
                                                            data-modal-target="confirm-restore-modal" 
                                                            data-modal-toggle="confirm-restore-modal"
                                                            data-backup-name={ backup.Name }
                                                            class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300">
                                                        <i class="fas fa-undo-alt"></i>
                                                    </button>
                                                    <a href={ templ.SafeURL("/admin/database/download-backup/" + backup.Name) } 
                                                       class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300">
                                                        <i class="fas fa-download"></i>
                                                    </a>
                                                    <button type="button"
                                                            data-modal-target="confirm-delete-modal"
                                                            data-modal-toggle="confirm-delete-modal"
                                                            data-backup-name={ backup.Name }
                                                            class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    }
                                }
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Upload Backup Section -->
                <div class="bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 mt-8">
                    <div class="p-6 border-b border-gray-200 dark:border-gray-700">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Restore from Backup File</h3>
                    </div>
                    <div class="p-6">
                        <form id="upload-backup-form" method="POST" action="/admin/database/restore-database" enctype="multipart/form-data">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Upload Backup File</label>
                                <div class="flex items-center justify-center w-full">
                                    <label class="flex flex-col w-full h-32 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700">
                                        <div class="flex flex-col items-center justify-center pt-5 pb-6">
                                            <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                            <p class="mb-2 text-sm text-gray-500 dark:text-gray-400"><span class="font-semibold">Click to upload</span> or drag and drop</p>
                                            <p class="text-xs text-gray-500 dark:text-gray-400">SQLite backup file</p>
                                        </div>
                                        <input type="file" name="backup_file" class="hidden" accept=".db,.sqlite,.backup" />
                                    </label>
                                </div>
                            </div>
                            <div class="flex items-center justify-end">
                                <button type="submit" class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 dark:bg-yellow-700 dark:hover:bg-yellow-800">
                                    <i class="fas fa-undo-alt mr-2"></i>
                                    Restore Database
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Help Section -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg shadow-sm mt-8 p-4 border border-gray-200 dark:border-gray-700">
                    <div class="flex items-start mb-2">
                        <div class="flex items-center h-5">
                            <i class="fas fa-info-circle w-4 h-4 text-blue-500 dark:text-blue-400 mr-2"></i>
                        </div>
                        <div class="ml-2 text-sm">
                            <h4 class="font-medium text-gray-900 dark:text-white">Important Safety Information</h4>
                            <ul class="mt-2 text-gray-600 dark:text-gray-400 space-y-1 list-disc list-inside">
                                <li>Always create a backup before making significant changes</li>
                                <li>Restoring a backup will overwrite all current data</li>
                                <li>Database optimization may take time for large databases</li>
                                <li>Clear job history operations cannot be undone</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Restore Confirmation Modal -->
        <div id="confirm-restore-modal" tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full bg-gray-900/50 dark:bg-gray-900/80 backdrop-blur-sm">
            <div class="relative p-4 w-full max-w-md max-h-full mx-auto">
                <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
                    <div class="p-6 text-center">
                        <i class="fas fa-exclamation-triangle text-yellow-400 text-3xl mb-4"></i>
                        <h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">Are you sure you want to restore this backup? This will overwrite your current database.</h3>
                        <form method="POST" id="restore-form" action="/admin/database/restore-database">
                            <input type="hidden" name="filename" id="restore-filename" value="" />
                            <button type="submit" class="text-white bg-yellow-600 hover:bg-yellow-800 focus:ring-4 focus:outline-none focus:ring-yellow-300 dark:focus:ring-yellow-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
                                Yes, restore it
                            </button>
                            <button type="button" data-modal-hide="confirm-restore-modal" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600">
                                No, cancel
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div id="confirm-delete-modal" tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full bg-gray-900/50 dark:bg-gray-900/80 backdrop-blur-sm">
            <div class="relative p-4 w-full max-w-md max-h-full mx-auto">
                <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
                    <div class="p-6 text-center">
                        <i class="fas fa-trash-alt text-red-400 text-3xl mb-4"></i>
                        <h3 class="mb-5 text-lg font-normal text-gray-500 dark:text-gray-400">Are you sure you want to delete this backup file?</h3>
                        <form method="POST" id="delete-form" action="">
                            <button type="submit" class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
                                Yes, delete it
                            </button>
                            <button type="button" data-modal-hide="confirm-delete-modal" class="text-gray-500 bg-white hover:bg-gray-100 focus:ring-4 focus:outline-none focus:ring-gray-200 rounded-lg border border-gray-200 text-sm font-medium px-5 py-2.5 hover:text-gray-900 focus:z-10 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600">
                                No, cancel
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <script>
            // Handle restore modal
            document.addEventListener('DOMContentLoaded', function() {
                // Parse URL parameters for error and status messages
                const urlParams = new URLSearchParams(window.location.search);
                const errorParam = urlParams.get('error');
                const detailsParam = urlParams.get('details');
                const statusParam = urlParams.get('status');
                
                // Function to create and show a toast
                function showToast(message, type) {
                    const toastContainer = document.getElementById('toast-container');
                    
                    // Create toast element
                    const toast = document.createElement('div');
                    toast.id = 'toast-' + type + '-' + Date.now();
                    toast.className = 'flex items-center w-full max-w-xs p-4 mb-4 rounded-lg shadow text-gray-500 bg-white dark:text-gray-400 dark:bg-gray-800 transform translate-y-16 opacity-0 transition-all duration-300 ease-out';
                    toast.role = 'alert';
                    
                    // Set toast content based on type
                    let iconClass, bgColorClass, textColorClass;
                    
                    if (type === 'success') {
                        iconClass = 'text-green-500 bg-green-100 dark:bg-green-800 dark:text-green-200';
                        bgColorClass = 'text-green-500 dark:text-green-200';
                        textColorClass = 'text-green-500 dark:text-green-200';
                    } else if (type === 'error') {
                        iconClass = 'text-red-500 bg-red-100 dark:bg-red-800 dark:text-red-200';
                        bgColorClass = 'text-red-500 dark:text-red-200';
                        textColorClass = 'text-red-500 dark:text-red-200';
                    } else {
                        iconClass = 'text-blue-500 bg-blue-100 dark:bg-blue-800 dark:text-blue-200';
                        bgColorClass = 'text-blue-500 dark:text-blue-200';
                        textColorClass = 'text-blue-500 dark:text-blue-200';
                    }
                    
                    // Set inner HTML with appropriate icon and message
                    toast.innerHTML = `
                        <div class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg ${iconClass}">
                            ${type === 'success' 
                              ? '<i class="fas fa-check"></i>' 
                              : type === 'error' 
                                ? '<i class="fas fa-exclamation-circle"></i>'
                                : '<i class="fas fa-info-circle"></i>'}
                        </div>
                        <div class="ml-3 text-sm font-normal">${message}</div>
                        <button type="button" class="ml-auto -mx-1.5 -my-1.5 bg-white text-gray-400 hover:text-gray-900 rounded-lg focus:ring-2 focus:ring-gray-300 p-1.5 hover:bg-gray-100 inline-flex h-8 w-8 dark:text-gray-500 dark:hover:text-white dark:bg-gray-800 dark:hover:bg-gray-700" data-dismiss-target="#${toast.id}" aria-label="Close">
                            <span class="sr-only">Close</span>
                            <i class="fas fa-times"></i>
                        </button>
                    `;
                    
                    // Add toast to container
                    toastContainer.appendChild(toast);
                    
                    // Trigger animation after a small delay to ensure the DOM has updated
                    setTimeout(() => {
                        toast.classList.remove('translate-y-16', 'opacity-0');
                        toast.classList.add('translate-y-0', 'opacity-100');
                    }, 10);
                    
                    // Add event listener to close button
                    const closeButton = toast.querySelector('button[data-dismiss-target]');
                    closeButton.addEventListener('click', function() {
                        // Animate out before removing
                        toast.classList.add('opacity-0', 'translate-y-4');
                        setTimeout(() => {
                            toast.remove();
                        }, 300);
                    });
                    
                    // Auto-remove toast after 5 seconds
                    setTimeout(() => {
                        toast.classList.add('opacity-0', 'translate-y-4');
                        setTimeout(() => {
                            toast.remove();
                        }, 300);
                    }, 5000);
                }
                
                // Display error message if present
                if (errorParam) {
                    const errorMessage = decodeURIComponent(errorParam).replace(/\+/g, ' ');
                    let details = '';
                    
                    if (detailsParam) {
                        details = decodeURIComponent(detailsParam).replace(/\+/g, ' ');
                    }
                    
                    const fullMessage = details ? `${errorMessage}: ${details}` : errorMessage;
                    showToast(fullMessage, 'error');
                }
                
                // Display status message if present
                if (statusParam) {
                    const statusMessage = decodeURIComponent(statusParam).replace(/\+/g, ' ');
                    showToast(statusMessage, 'success');
                }
            
                // Display modals when buttons are clicked
                const restoreButtons = document.querySelectorAll('[data-modal-target="confirm-restore-modal"]');
                restoreButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const backupName = this.getAttribute('data-backup-name');
                        document.getElementById('restore-filename').value = backupName;
                        document.getElementById('restore-form').action = `/admin/database/restore-database/${backupName}`;
                        
                        // Show the modal
                        const modal = document.getElementById('confirm-restore-modal');
                        modal.classList.remove('hidden');
                        modal.classList.add('flex');
                    });
                });

                // Handle delete modal
                const deleteButtons = document.querySelectorAll('[data-modal-target="confirm-delete-modal"]');
                deleteButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const backupName = this.getAttribute('data-backup-name');
                        document.getElementById('delete-form').action = `/admin/database/delete-backup/${backupName}`;
                        
                        // Show the modal
                        const modal = document.getElementById('confirm-delete-modal');
                        modal.classList.remove('hidden');
                        modal.classList.add('flex');
                    });
                });
                
                // Handle modal hide buttons
                const hideButtons = document.querySelectorAll('[data-modal-hide]');
                hideButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const modalId = this.getAttribute('data-modal-hide');
                        const modal = document.getElementById(modalId);
                        modal.classList.add('hidden');
                        modal.classList.remove('flex');
                    });
                });

                // File upload preview
                const fileInput = document.querySelector('input[type="file"]');
                if (fileInput) {
                    fileInput.addEventListener('change', function(e) {
                        const fileName = e.target.files[0]?.name || 'No file selected';
                        const fileLabel = this.parentElement.querySelector('p.mb-2');
                        if (fileLabel) {
                            fileLabel.textContent = fileName;
                        }
                    });
                }
                
                // Add form submission events
                const backupForm = document.getElementById('backup-form');
                if (backupForm) {
                    backupForm.addEventListener('submit', function(e) {
                        console.log('Backup form submitted');
                    });
                }
                
                const vacuumForm = document.getElementById('vacuum-form');
                if (vacuumForm) {
                    vacuumForm.addEventListener('submit', function(e) {
                        console.log('Vacuum form submitted');
                    });
                }
                
                const clearJobForm = document.getElementById('clear-job-form');
                if (clearJobForm) {
                    clearJobForm.addEventListener('submit', function(e) {
                        console.log('Clear job form submitted');
                    });
                }
            });

            // Set dark background color if in dark mode
            if (document.documentElement.classList.contains('dark')) {
                document.getElementById('database-tools-container').style.backgroundColor = '#111827';
            }
            
            // Add event listener for theme changes
            document.addEventListener('DOMContentLoaded', function() {
                const themeToggle = document.getElementById('theme-toggle');
                if (themeToggle) {
                    themeToggle.addEventListener('click', function() {
                        setTimeout(function() {
                            const isDark = document.documentElement.classList.contains('dark');
                            document.getElementById('database-tools-container').style.backgroundColor = isDark ? '#111827' : 'rgb(249, 250, 251)';
                        }, 50);
                    });
                }
            });
        </script>
    }
} 