{% extends "base.html" %}

{% block content %}


<!-- Create Form (hidden by default) -->
<div class="row mb-4" id="createForm" style="display: none;">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5><i class="fas fa-plus me-2"></i>Create Scheduled Job</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="/jobs/create">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="name" class="form-label">Job Name</label>
                                <input type="text" class="form-control" id="name" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="prompt_id" class="form-label">Prompt</label>
                                <select class="form-control" id="prompt_id" name="prompt_id" required>
                                    <option value="">Select a prompt...</option>
                                    {% for prompt in prompts %}
                                    <option value="{{ prompt.id }}">{{ prompt.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="cron_expression" class="form-label">Cron Expression</label>
                        <input type="text" class="form-control" id="cron_expression" name="cron_expression" required placeholder="e.g., 0 9 * * * (daily at 9 AM)">
                        <div class="form-text">
                            Examples: <code>0 9 * * *</code> (Daily at 9 AM), <code>*/15 * * * *</code> (Every 15 minutes), <code>0 0 * * 1</code> (Weekly on Monday)
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save me-2"></i>Create Job
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="hideCreateForm()">
                            <i class="fas fa-times me-2"></i>Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Jobs List -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Jobs</h5>
                    <button class="btn btn-primary btn-sm" id="showCreateFormBtn" onclick="showCreateForm()">
                        <i class="fas fa-plus me-2"></i>New
                    </button>
                </div>
            </div>
            <div class="card-body">
                {% if jobs %}
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Prompt</th>
                                    <th>Schedule</th>
                                    <th>Status</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for job in jobs %}
                                <tr id="job-{{ job.id }}">
                                    <td><strong>{{ job.name }}</strong></td>
                                    <td>{{ job.prompt.name }}</td>
                                    <td><code>{{ job.cron_expression }}</code></td>
                                    <td>
                                        {% if job.is_active %}
                                            <span class="badge bg-success">Active</span>
                                        {% else %}
                                            <span class="badge bg-secondary">Inactive</span>
                                        {% endif %}
                                    </td>
                                    <td>{{ job.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button class="btn btn-sm btn-outline-primary" onclick="toggleJob('{{ job.id }}')" title="{% if job.is_active %}Pause{% else %}Resume{% endif %}">
                                                {% if job.is_active %}
                                                    <i class="fas fa-pause"></i>
                                                {% else %}
                                                    <i class="fas fa-play"></i>
                                                {% endif %}
                                            </button>
                                            <button class="btn btn-sm btn-outline-info" onclick="viewExecutions('{{ job.id }}', '{{ job.name }}')" title="View History">
                                                <i class="fas fa-history"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="deleteJob('{{ job.id }}')" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                {% else %}
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-inbox me-2"></i>No scheduled jobs created yet. 
                        <button class="btn btn-link p-0" onclick="showCreateForm()">Create your first job</button>.
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Modal for viewing execution history -->
<div class="modal fade" id="executionHistoryModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="executionHistoryTitle">Execution History</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="executionHistoryLoading" class="text-center">
                    <i class="fas fa-spinner fa-spin me-2"></i>Loading execution history...
                </div>
                <div id="executionHistoryContent" style="display: none;">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Started</th>
                                    <th>Duration</th>
                                    <th>Status</th>
                                    <th>Output Preview</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="executionHistoryTableBody">
                            </tbody>
                        </table>
                    </div>
                    <div id="executionHistoryEmpty" class="text-center text-muted" style="display: none;">
                        <i class="fas fa-inbox me-2"></i>No executions found for this job.
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal for viewing full execution output -->
<div class="modal fade" id="executionDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="executionDetailTitle">Execution Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Started:</strong>
                        <span id="executionDetailStarted"></span>
                    </div>
                    <div class="col-md-6">
                        <strong>Completed:</strong>
                        <span id="executionDetailCompleted"></span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>Status:</strong>
                        <span id="executionDetailStatus"></span>
                    </div>
                    <div class="col-md-6">
                        <strong>Duration:</strong>
                        <span id="executionDetailDuration"></span>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-12">
                        <strong>Session ID:</strong>
                        <code id="executionDetailSessionId" class="text-muted"></code>
                    </div>
                </div>
                <div id="executionDetailOutput" style="display: none;">
                    <strong>Output:</strong>
                    <pre id="executionDetailOutputContent" class="bg-light p-3 mt-2"></pre>
                </div>
                <div id="executionDetailError" style="display: none;">
                    <strong>Error:</strong>
                    <pre id="executionDetailErrorContent" class="bg-danger-subtle p-3 mt-2 text-danger"></pre>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="viewSessionButton" onclick="viewSession()" style="display: none;">
                    <i class="fas fa-comments me-2"></i>View Session
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// Handle create form visibility
function showCreateForm() {
    document.getElementById('createForm').style.display = 'block';
    document.getElementById('showCreateFormBtn').style.display = 'none';
    document.getElementById('name').focus();
}

function hideCreateForm() {
    document.getElementById('createForm').style.display = 'none';
    document.getElementById('showCreateFormBtn').style.display = 'inline-block';
}

// Check if we should show create form on load
document.addEventListener('DOMContentLoaded', function() {
    if (window.location.hash === '#create') {
        showCreateForm();
    }
});

function toggleJob(id) {
    fetch(`/api/jobs/${id}/toggle`, { method: 'PUT' })
        .then(() => location.reload())
        .catch(error => alert('Error toggling job: ' + error));
}

function deleteJob(id) {
    if (confirm('Are you sure you want to delete this job?')) {
        fetch(`/api/jobs/${id}`, { method: 'DELETE' })
            .then(() => location.reload())
            .catch(error => alert('Error deleting job: ' + error));
    }
}

// Store the current job ID and execution data globally
let currentViewingJobId = null;
let currentExecutions = null;
let currentSessionId = null;

function viewExecutions(jobId, jobName) {
    currentViewingJobId = jobId;
    
    // Set modal title and show loading
    document.getElementById('executionHistoryTitle').textContent = `Execution History: ${jobName}`;
    document.getElementById('executionHistoryLoading').style.display = 'block';
    document.getElementById('executionHistoryContent').style.display = 'none';
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('executionHistoryModal'));
    modal.show();
    
    // Fetch execution history
    fetch(`/api/jobs/${jobId}/executions`)
        .then(response => response.json())
        .then(executions => {
            currentExecutions = executions; // Store for detail viewing
            
            document.getElementById('executionHistoryLoading').style.display = 'none';
            document.getElementById('executionHistoryContent').style.display = 'block';
            
            const tbody = document.getElementById('executionHistoryTableBody');
            tbody.innerHTML = '';
            
            if (executions.length === 0) {
                document.getElementById('executionHistoryEmpty').style.display = 'block';
                return;
            }
            
            executions.forEach(execution => {
                const row = document.createElement('tr');
                
                // Format timestamps
                const startedAt = new Date(execution.started_at).toLocaleString();
                
                // Calculate duration
                let duration = '-';
                if (execution.completed_at) {
                    const start = new Date(execution.started_at);
                    const end = new Date(execution.completed_at);
                    const diffSeconds = Math.floor((end - start) / 1000);
                    if (diffSeconds < 60) {
                        duration = `${diffSeconds}s`;
                    } else {
                        duration = `${Math.floor(diffSeconds / 60)}m ${diffSeconds % 60}s`;
                    }
                } else if (execution.status === 'running') {
                    duration = 'Running...';
                }
                
                // Status badge
                let statusBadge = '';
                if (execution.status === 'completed') {
                    statusBadge = '<span class="badge bg-success">Completed</span>';
                } else if (execution.status === 'failed') {
                    statusBadge = '<span class="badge bg-danger">Failed</span>';
                } else if (execution.status === 'running') {
                    statusBadge = '<span class="badge bg-primary">Running</span>';
                } else {
                    statusBadge = `<span class="badge bg-secondary">${execution.status}</span>`;
                }
                
                // Output preview
                let outputPreview = '-';
                if (execution.output) {
                    outputPreview = execution.output.substring(0, 50);
                    if (execution.output.length > 50) {
                        outputPreview += '...';
                    }
                } else if (execution.error_message) {
                    outputPreview = `Error: ${execution.error_message.substring(0, 30)}...`;
                }
                
                // Actions
                const actions = (execution.output || execution.error_message) ? 
                    `<button class="btn btn-sm btn-outline-primary" onclick="showExecutionDetails(${execution.id})" title="View Details">
                        <i class="fas fa-eye"></i>
                    </button>` : '-';
                
                row.innerHTML = `
                    <td>${startedAt}</td>
                    <td>${duration}</td>
                    <td>${statusBadge}</td>
                    <td><small>${outputPreview}</small></td>
                    <td>${actions}</td>
                `;
                
                tbody.appendChild(row);
            });
        })
        .catch(error => {
            document.getElementById('executionHistoryLoading').style.display = 'none';
            document.getElementById('executionHistoryContent').innerHTML = 
                '<div class="alert alert-danger">Error loading execution history: ' + error + '</div>';
            document.getElementById('executionHistoryContent').style.display = 'block';
        });
}

function showExecutionDetails(executionId) {
    // Find the execution in our stored data
    const execution = currentExecutions.find(ex => ex.id === executionId);
    if (!execution) {
        alert('Execution not found');
        return;
    }
    
    // Populate the detail modal
    document.getElementById('executionDetailTitle').textContent = `Execution #${execution.id}`;
    document.getElementById('executionDetailStarted').textContent = new Date(execution.started_at).toLocaleString();
    document.getElementById('executionDetailCompleted').textContent = 
        execution.completed_at ? new Date(execution.completed_at).toLocaleString() : 'Not completed';
    
    // Status with color
    const statusElement = document.getElementById('executionDetailStatus');
    statusElement.innerHTML = execution.status === 'completed' ? 
        '<span class="badge bg-success">Completed</span>' :
        execution.status === 'failed' ?
        '<span class="badge bg-danger">Failed</span>' :
        execution.status === 'running' ?
        '<span class="badge bg-primary">Running</span>' :
        `<span class="badge bg-secondary">${execution.status}</span>`;
    
    // Duration
    let duration = 'Not calculated';
    if (execution.completed_at) {
        const start = new Date(execution.started_at);
        const end = new Date(execution.completed_at);
        const diffSeconds = Math.floor((end - start) / 1000);
        duration = diffSeconds < 60 ? `${diffSeconds} seconds` : 
                  `${Math.floor(diffSeconds / 60)} minutes ${diffSeconds % 60} seconds`;
    }
    document.getElementById('executionDetailDuration').textContent = duration;
    
    // Session ID
    document.getElementById('executionDetailSessionId').textContent = execution.session_id || 'Not available';
    
    // Store session ID and show/hide session button
    currentSessionId = execution.session_id;
    const sessionButton = document.getElementById('viewSessionButton');
    if (currentSessionId) {
        sessionButton.style.display = 'inline-block';
    } else {
        sessionButton.style.display = 'none';
    }
    
    // Output or error
    const outputDiv = document.getElementById('executionDetailOutput');
    const errorDiv = document.getElementById('executionDetailError');
    
    if (execution.output) {
        document.getElementById('executionDetailOutputContent').textContent = execution.output;
        outputDiv.style.display = 'block';
        errorDiv.style.display = 'none';
    } else if (execution.error_message) {
        document.getElementById('executionDetailErrorContent').textContent = execution.error_message;
        errorDiv.style.display = 'block';
        outputDiv.style.display = 'none';
    } else {
        outputDiv.style.display = 'none';
        errorDiv.style.display = 'none';
    }
    
    // Show the detail modal
    new bootstrap.Modal(document.getElementById('executionDetailModal')).show();
}

function viewSession() {
    if (currentSessionId) {
        // Open session history in new tab
        window.open(`/sessions/${currentSessionId}`, '_blank');
    } else {
        alert('No session ID available for this execution');
    }
}
</script>
{% endblock %}