/**
 * Task Manager JavaScript
 * Handles task list functionality, polling, and UI updates
 */

// Task management variables
var taskPollingInterval = null;
var isLoadingTasks = false; // Prevent concurrent task list requests

// Get translations with fallback
var trans = window.taskManagerTranslations || {};

// Load and apply saved height
function loadTaskListHeight() {
    // Always use constant height on load
    var taskList = document.getElementById('fixedTaskList');
    if (taskList) {
        taskList.style.height = '250px';
    }
}

// Save task list height
function saveTaskListHeight(height) {
    sessionStorage.setItem('taskListHeight', height);
}

// Toggle task list minimize/maximize
function toggleTaskList() {
    var taskList = document.getElementById('fixedTaskList');
    var taskBody = taskList.querySelector('.task-list-body');
    var toggleIcon = document.getElementById('taskListToggleIcon');
    var resizeHandle = taskList.querySelector('.task-list-resize-handle');
    
    if (taskBody.style.display === 'none') {
        // Maximize - show content and animate height
        toggleIcon.className = 'ri-subtract-line';
        taskList.classList.remove('minimized');
        
        // Save state immediately
        sessionStorage.setItem('taskListMinimized', 'false');
        
        // Get current height (header only) before expanding
        var currentHeight = taskList.offsetHeight;
        
        // Set explicit height to enable animation from current height
        taskList.style.height = currentHeight + 'px';
        
        // Show content and animate height
        taskBody.style.display = '';
        requestAnimationFrame(function() {
            taskList.style.height = '250px';
        });
    } else {
        // Minimize - animate height then hide content
        toggleIcon.className = 'ri-add-line';
        
        // Save state immediately
        sessionStorage.setItem('taskListMinimized', 'true');
        
        // First animate height to just the header
        var headerHeight = taskList.querySelector('.task-list-header').offsetHeight;
        taskList.style.height = headerHeight + 'px';
        
        // After height animation completes, hide content
        setTimeout(function() {
            taskBody.style.display = 'none';
            taskList.classList.add('minimized');
            taskList.style.height = 'auto';
        }, 300);
    }
}

// Initialize resize functionality
function initResizeTaskList() {
    var taskList = document.getElementById('fixedTaskList');
    if (!taskList) return;
    
    var resizeHandle = taskList.querySelector('.task-list-resize-handle');
    var isResizing = false;
    var startY = 0;
    var startHeight = 0;
    
    resizeHandle.addEventListener('mousedown', function(e) {
        isResizing = true;
        startY = e.clientY;
        startHeight = taskList.offsetHeight;
        document.body.style.cursor = 'ns-resize';
        taskList.classList.add('resizing');
        e.preventDefault();
        
        // If minimized, maximize it when user starts resizing
        var taskBody = taskList.querySelector('.task-list-body');
        if (taskBody.style.display === 'none') {
            toggleTaskList();
        }
    });
    
    document.addEventListener('mousemove', function(e) {
        if (!isResizing) return;
        
        var deltaY = startY - e.clientY;
        var newHeight = startHeight + deltaY;
        
        // Enforce min/max height (50% of viewport height)
        newHeight = Math.max(50, Math.min(window.innerHeight * 0.5, newHeight));
        
        taskList.style.height = newHeight + 'px';
    });
    
    document.addEventListener('mouseup', function() {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = '';
            taskList.classList.remove('resizing');
            saveTaskListHeight(taskList.offsetHeight);
        }
    });
    
    // Touch support
    resizeHandle.addEventListener('touchstart', function(e) {
        isResizing = true;
        startY = e.touches[0].clientY;
        startHeight = taskList.offsetHeight;
        taskList.classList.add('resizing');
        e.preventDefault();
        
        // If minimized, maximize it when user starts resizing
        var taskBody = taskList.querySelector('.task-list-body');
        if (taskBody.style.display === 'none') {
            toggleTaskList();
        }
    });
    
    document.addEventListener('touchmove', function(e) {
        if (!isResizing) return;
        
        var deltaY = startY - e.touches[0].clientY;
        var newHeight = startHeight + deltaY;
        
        // Enforce min/max height (50% of viewport height)
        newHeight = Math.max(50, Math.min(window.innerHeight * 0.5, newHeight));
        
        taskList.style.height = newHeight + 'px';
    });
    
    document.addEventListener('touchend', function() {
        if (isResizing) {
            isResizing = false;
            taskList.classList.remove('resizing');
            saveTaskListHeight(taskList.offsetHeight);
        }
    });
}

// Load tasks from database
function loadTasksFromDatabase() {
    // Prevent concurrent requests
    if (isLoadingTasks) {
        return;
    }

    isLoadingTasks = true;

    $.ajax({
        url: '/task/list',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                updateTaskListUI(response.tasks);
            }
        },
        error: function() {
            console.error('Failed to load tasks from database');
        },
        complete: function() {
            // Always reset flag when request completes (success or error)
            isLoadingTasks = false;
        }
    });
}

// Update task list UI
function updateTaskListUI(tasks) {
    var tbody = document.getElementById('taskListTableBody');
    if (!tbody) return;

    tbody.innerHTML = '';

    if (!tasks || tasks.length === 0) {
        // Adjust colspan based on screen size
        var colspan = window.innerWidth <= 767 ? 3 : 6;
        tbody.innerHTML = '<tr class="no-tasks"><td colspan="' + colspan + '" class="text-center text-muted py-3"><small>' + (trans.noRunningTasks || 'No running tasks') + '</small></td></tr>';
        return;
    }

    tasks.forEach(function(task) {
        var row = document.createElement('tr');
        row.style.cursor = 'pointer';
        row.setAttribute('onclick', 'showTaskDetails(\'' + task.id + '\')');
        row.setAttribute('title', trans.clickToViewDetails || 'Click to view task details');

        var taskName = task.name || task.task_type;
        var taskNameHtml = '<small class="fw-medium">' + taskName + '</small>';

        // Format timestamps
        var startTime = task.start_time ? formatDateTime(task.start_time) : '-';
        var endTime = task.end_time ? formatDateTime(task.end_time) : '-';
        var startedBy = task.started_by || task.username || '-';
        // Create progress cell with percentage on same line
        var progressHtml = '<div class="task-progress-wrapper">' +
            '<div class="task-progress-mini"><div class="progress-bar ' + task.status + '" style="width: ' + (task.progress || 0) + '%"></div></div>' +
            '<span class="task-progress-percent">' + (task.progress || 0) + '%</span>' +
            '</div>';
        row.innerHTML = '<td class="small task-col-name">' + taskNameHtml + '</td>' +
            '<td class="small task-col-status"><span class="badge bg-' + getStatusColor(task.status) + '-subtle text-' + getStatusColor(task.status) + ' text-uppercase">' +
            task.status.replace(/_/g, ' ') + '</span></td>' +
            '<td class="small task-col-user">' + startedBy + '</td>' +
            '<td class="small task-col-start">' + startTime + '</td>' +
            '<td class="small task-col-end">' + endTime + '</td>' +
            '<td class="small task-col-progress">' + progressHtml + '</td>';
        tbody.appendChild(row);

        // Check if this is a newly completed task that needs redirect
        checkForTaskRedirect(task);
    });
}

// Check if a completed task should trigger a redirect
function checkForTaskRedirect(task) {
    // Only handle completed tasks
    if (task.status !== 'completed') {
        return;
    }

    // Check if we've already handled this task's redirect globally (across all tabs)
    var handledTasks = JSON.parse(localStorage.getItem('handledTaskRedirects') || '[]');
    if (handledTasks.includes(task.id)) {
        return;
    }

    // Only redirect if THIS tab created the task
    var myTasks = JSON.parse(sessionStorage.getItem('myCreatedTasks') || '[]');
    if (!myTasks.includes(task.id)) {
        return; // This tab didn't create this task, don't redirect
    }

    // Handle different task types
    if (task.task_type === 'vm_creation' && task.result_data && task.result_data.vm_uuid) {
        // Mark as handled globally before showing prompt
        markTaskRedirectHandled(task.id);

        // Remove from this tab's created tasks list
        removeFromMyCreatedTasks(task.id);

        // Ask user if they want to redirect
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                icon: 'success',
                title: trans.vmCreatedSuccessfully || 'VM Created Successfully',
                text: trans.viewNewlyCreatedVM || 'Would you like to view the newly created virtual machine?',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#6c757d',
                confirmButtonText: trans.yesViewVM || 'Yes, view VM',
                cancelButtonText: trans.stayHere || 'Stay here'
            }).then((result) => {
                if (result.isConfirmed) {
                    // User wants to redirect
                    window.location.href = '/virtual-machine/view?id=' + task.result_data.vm_uuid;
                }
                // If cancelled, user stays on current page
            });
        } else {
            // Fallback if Swal is not available
            if (confirm(trans.vmCreatedConfirm || 'VM created successfully! Would you like to view it?')) {
                window.location.href = '/virtual-machine/view?id=' + task.result_data.vm_uuid;
            }
        }
    }
    // Handle VM clone task completion
    else if (task.task_type === 'vm_clone' && task.result_data && task.result_data.vm_id) {
        // Mark as handled globally before showing prompt
        markTaskRedirectHandled(task.id);

        // Remove from this tab's created tasks list
        removeFromMyCreatedTasks(task.id);

        // Ask user if they want to redirect
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                icon: 'success',
                title: trans.vmClonedSuccessfully || 'VM Cloned Successfully',
                text: trans.viewClonedVM || 'Would you like to view the cloned virtual machine?',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#6c757d',
                confirmButtonText: trans.yesViewVM || 'Yes, view VM',
                cancelButtonText: trans.stayHere || 'Stay here'
            }).then((result) => {
                if (result.isConfirmed) {
                    // User wants to redirect
                    window.location.href = '/virtual-machine/view?id=' + task.result_data.vm_id;
                }
                // If cancelled, user stays on current page
            });
        } else {
            // Fallback if Swal is not available
            if (confirm(trans.vmClonedConfirm || 'VM cloned successfully! Would you like to view it?')) {
                window.location.href = '/virtual-machine/view?id=' + task.result_data.vm_id;
            }
        }
    }
}

// Mark task redirect as handled globally (across all tabs)
function markTaskRedirectHandled(taskId) {
    var handledTasks = JSON.parse(localStorage.getItem('handledTaskRedirects') || '[]');
    if (!handledTasks.includes(taskId)) {
        handledTasks.push(taskId);
        localStorage.setItem('handledTaskRedirects', JSON.stringify(handledTasks));
    }
}

// Track that this tab created a specific task
function trackMyCreatedTask(taskId) {
    var myTasks = JSON.parse(sessionStorage.getItem('myCreatedTasks') || '[]');
    if (!myTasks.includes(taskId)) {
        myTasks.push(taskId);
        sessionStorage.setItem('myCreatedTasks', JSON.stringify(myTasks));
    }
}

// Expose globally for use in other scripts
window.trackMyCreatedTask = trackMyCreatedTask;

// Remove task from this tab's created tasks list
function removeFromMyCreatedTasks(taskId) {
    var myTasks = JSON.parse(sessionStorage.getItem('myCreatedTasks') || '[]');
    var index = myTasks.indexOf(taskId);
    if (index > -1) {
        myTasks.splice(index, 1);
        sessionStorage.setItem('myCreatedTasks', JSON.stringify(myTasks));
    }
}

// Get status color
function getStatusColor(status) {
    switch(status) {
        case 'completed': return 'success';
        case 'failed': return 'danger';
        case 'in_progress': return 'primary';
        case 'processing': return 'primary';
        case 'queued': return 'info';
        case 'cancelled': return 'warning';
        case 'pending': return 'secondary';
        default: return 'secondary';
    }
}

// Get task display name
function getTaskDisplayName(taskType) {
    var names = {
        'external_network_creation': 'External Network Creation',
        'vm_creation': 'Virtual Machine Creation',
        'vm_clone': 'Virtual Machine Clone',
        'vm_delete': 'Virtual Machine Deletion',
        'backup_create': 'Backup Creation',
        'backup_restore': 'Backup Restoration',
        'vdc_creation': 'Virtual Data Center Creation'
    };
    
    return names[taskType] || taskType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
}

// Format date time for display
// Server already returns dates formatted according to user preferences via DateTimeHelper::formatForUser()
// So we just return the timestamp as-is without reformatting
function formatDateTime(timestamp) {
    if (!timestamp) return '-';

    // Return the already-formatted date string from server
    return timestamp;
}

// Show task details
function showTaskDetails(taskId) {
    // Load task details via AJAX
    $.ajax({
        url: '/task/details',
        type: 'GET',
        data: { taskId: taskId },
        success: function(response) {
            // Show the modal with the loaded content
            $('#taskDetailsModal .modal-content').html(response);
            // Add modal-xl class to make it extra large
            $('#taskDetailsModal .modal-dialog').addClass('modal-xl');
            $('#taskDetailsModal').modal('show');
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: trans.error || 'Error',
                text: trans.failedToLoadDetails || 'Failed to load task details'
            });
        }
    });
}

// Remove individual task
function removeTask(taskId) {
    // Show confirmation
    Swal.fire({
        title: trans.areYouSure || 'Are you sure?',
        text: trans.removeTaskConfirm || 'Do you want to remove this task?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: trans.yesRemoveIt || 'Yes, remove it!'
    }).then((result) => {
        if (result.isConfirmed) {
            var csrfToken = $('meta[name="csrf-token"]').attr('content');
            var csrfParam = $('meta[name="csrf-param"]').attr('content') || '_csrf-backend';
            
            var data = { taskId: taskId };
            if (csrfToken) {
                data[csrfParam] = csrfToken;
            }
            
            $.ajax({
                url: '/task/remove',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        loadTasksFromDatabase();
                        Swal.fire(
                            trans.removed || 'Removed!',
                            trans.taskRemoved || 'The task has been removed.',
                            trans.success || 'success'
                        );
                    }
                },
                error: function() {
                    console.error('Failed to remove task');
                    Swal.fire(
                        trans.errorExclamation || 'Error!',
                        trans.failedToRemove || 'Failed to remove the task.',
                        'error'
                    );
                }
            });
        }
    });
}

// Retry failed task
function retryTask(taskId) {
    // Show confirmation
    Swal.fire({
        title: trans.retryTask || 'Retry Task?',
        text: trans.retryTaskConfirm || 'Do you want to retry this failed task?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#6c757d',
        confirmButtonText: trans.yesRetryIt || 'Yes, retry it!'
    }).then((result) => {
        if (result.isConfirmed) {
            var csrfToken = $('meta[name="csrf-token"]').attr('content');
            var csrfParam = $('meta[name="csrf-param"]').attr('content') || '_csrf-backend';
            
            var data = { taskId: taskId };
            if (csrfToken) {
                data[csrfParam] = csrfToken;
            }
            
            $.ajax({
                url: '/task/retry',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Show success notification
                        Swal.fire({
                            icon: 'success',
                            title: trans.taskRetryStarted || 'Task Retry Started',
                            text: trans.taskRestarted || 'The task has been restarted. You can monitor the progress below.',
                            timer: 3000,
                            showConfirmButton: false
                        });

                        // Refresh task list to show new task
                        loadTasksFromDatabase();
                    } else {
                        // Show error
                        Swal.fire({
                            icon: 'error',
                            title: trans.retryFailed || 'Retry Failed',
                            text: response.message || (trans.failedToRetry || 'Failed to retry the task')
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: trans.error || 'Error',
                        text: trans.errorRetrying || 'An error occurred while retrying the task'
                    });
                }
            });
        }
    });
}

// Stop task
function stopTask(taskId) {
    // Show confirmation
    Swal.fire({
        title: trans.areYouSure || 'Are you sure?',
        text: trans.stopTaskConfirm || 'Do you want to stop this task? This will mark it as failed and it can then be retried.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: trans.yesStopIt || 'Yes, stop it!'
    }).then((result) => {
        if (result.isConfirmed) {
            var csrfToken = $('meta[name="csrf-token"]').attr('content');
            var csrfParam = $('meta[name="csrf-param"]').attr('content') || '_csrf-backend';
            
            var data = { taskId: taskId };
            if (csrfToken) {
                data[csrfParam] = csrfToken;
            }
            
            $.ajax({
                url: '/task/stop',
                type: 'POST',
                data: data,
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Show success notification
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'warning',
                                title: trans.taskStopped || 'Task Stopped',
                                text: trans.taskStoppedMsg || 'The task has been stopped. You can now retry it if needed.',
                                timer: 3000,
                                showConfirmButton: false
                            });
                        }

                        // Refresh task list to show updated status
                        loadTasksFromDatabase();
                    } else {
                        // Show error
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'error',
                                title: trans.stopFailed || 'Stop Failed',
                                text: response.message || (trans.failedToStop || 'Failed to stop the task')
                            });
                        } else {
                            alert((trans.failedToStopPrefix || 'Failed to stop task: ') + (response.message || 'Unknown error'));
                        }
                    }
                },
                error: function() {
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            icon: 'error',
                            title: trans.error || 'Error',
                            text: trans.errorStopping || 'An error occurred while stopping the task'
                        });
                    } else {
                        alert(trans.errorStopping || 'An error occurred while stopping the task');
                    }
                }
            });
        }
    });
}

// Clear all completed and failed tasks
function clearCompletedTasks() {
    // Show confirmation
    if (confirm(trans.clearCompletedConfirm || 'Are you sure you want to clear all completed, failed, and cancelled tasks?')) {
        var csrfToken = $('meta[name="csrf-token"]').attr('content');
        var csrfParam = $('meta[name="csrf-param"]').attr('content') || '_csrf-backend';
        
        var data = {};
        if (csrfToken) {
            data[csrfParam] = csrfToken;
        }
        
        $.ajax({
            url: '/task/clear-completed',
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    loadTasksFromDatabase();
                }
            },
            error: function() {
                console.error('Failed to clear completed tasks');
            }
        });
    }
}

// Poll for task updates
function startTaskPolling() {
    if (taskPollingInterval) return;
    
    taskPollingInterval = setInterval(function() {
        loadTasksFromDatabase();
    }, 2000); // Poll every 2 seconds
}


// Handle sidebar size changes
function observeSidebarChanges() {
    // Simple approach - let CSS handle everything
    // The CSS transitions should work automatically when data-sidebar-size changes
}

// Initialize on page load
$(document).ready(function() {
    loadTasksFromDatabase();
    loadTaskListHeight();
    initResizeTaskList();
    startTaskPolling();
    observeSidebarChanges();

    // Restore minimized state only if explicitly saved
    var savedState = sessionStorage.getItem('taskListMinimized');

    // Only change from default if there's a saved state
    if (savedState !== null) {
        var taskList = document.getElementById('fixedTaskList');
        if (taskList) {
            var taskBody = taskList.querySelector('.task-list-body');
            var toggleIcon = document.getElementById('taskListToggleIcon');

            if (savedState === 'true') {
                // User explicitly minimized - restore that state
                taskBody.style.display = 'none';
                toggleIcon.className = 'ri-add-line';
                taskList.classList.add('minimized');
                taskList.style.height = 'auto';
            }
            // If savedState === 'false', it's already expanded by default
        }
    }
    // If no saved state, keep default expanded state (250px height already set by loadTaskListHeight)
});

// Global function to start tracking a task (simplified - just refresh the list)
window.trackTask = function(taskId, taskName, taskType) {
    // Mark this task as created by THIS tab
    trackMyCreatedTask(taskId);

    // Just refresh the task list from database
    loadTasksFromDatabase();
};

// Retry task from modal
window.retryTaskFromModal = function(taskId) {
    // Close the modal first
    $('#taskDetailsModal').modal('hide');
    
    // Call the retry function
    retryTask(taskId);
};

// Stop task from modal
window.stopTaskFromModal = function(taskId) {
    // Close the modal first
    $('#taskDetailsModal').modal('hide');
    
    // Call the stop function
    stopTask(taskId);
};

// Remove task from modal
window.removeTaskFromModal = function(taskId) {
    // Close the modal first
    $('#taskDetailsModal').modal('hide');
    
    // Call the remove function
    removeTask(taskId);
};

// Clean up task details modal when hidden
$(document).on('hidden.bs.modal', '#taskDetailsModal', function() {
    // Remove modal-xl class
    $('#taskDetailsModal .modal-dialog').removeClass('modal-xl');
    // Clear modal content to prevent old content from persisting
    $('#taskDetailsModal .modal-content').empty();
});

// Backward compatibility - redirect old function name to new one
window.forceFailTaskFromModal = window.stopTaskFromModal;
window.forceFailTask = window.stopTask;