{% extends "base.html" %}
{% from "macros/ui.html" import btn, btn_link, badge, alert, card, table, empty_state, spinner, modal, info_row, code_block %}

{% block title %}Job Queue - MySQL to Sheets Sync{% endblock %}
{% block page_title %}Job Queue{% endblock %}

{% block content %}
<div id="alertContainer"></div>

{# Queue Statistics Card #}
{% call card(title="Queue Statistics") %}
<div class="flex justify-between items-center mb-4">
    <div class="flex flex-wrap gap-6 text-sm">
        <div class="flex items-center gap-2">
            <span class="text-slate-500 dark:text-slate-400">Pending:</span>
            <span class="font-semibold text-amber-600 dark:text-amber-400" id="statPending">-</span>
        </div>
        <div class="flex items-center gap-2">
            <span class="text-slate-500 dark:text-slate-400">Running:</span>
            <span class="font-semibold text-blue-600 dark:text-blue-400" id="statRunning">-</span>
        </div>
        <div class="flex items-center gap-2">
            <span class="text-slate-500 dark:text-slate-400">Completed:</span>
            <span class="font-semibold text-green-600 dark:text-green-400" id="statCompleted">-</span>
        </div>
        <div class="flex items-center gap-2">
            <span class="text-slate-500 dark:text-slate-400">Failed:</span>
            <span class="font-semibold text-red-600 dark:text-red-400" id="statFailed">-</span>
        </div>
        <div class="flex items-center gap-2">
            <span class="text-slate-500 dark:text-slate-400">Total:</span>
            <span class="font-semibold text-slate-900 dark:text-white" id="statTotal">-</span>
        </div>
    </div>
    <label class="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 cursor-pointer">
        <input type="checkbox" id="autoRefreshToggle" onchange="toggleAutoRefresh()" class="h-4 w-4 rounded border-slate-300 dark:border-slate-600 dark:bg-slate-800 text-blue-600 focus:ring-blue-500">
        <span>Auto-refresh</span>
    </label>
</div>
{% endcall %}

{# Jobs Table Card #}
{% call card(title="Jobs") %}
{# Toolbar #}
<div class="flex justify-between items-center mb-4">
    <div class="flex flex-wrap gap-3">
        <select id="statusFilter" onchange="loadJobs()" class="px-3 py-2 text-sm border border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
            <option value="">All Statuses</option>
            <option value="pending">Pending</option>
            <option value="running">Running</option>
            <option value="completed">Completed</option>
            <option value="failed">Failed</option>
            <option value="cancelled">Cancelled</option>
        </select>
        <select id="typeFilter" onchange="loadJobs()" class="px-3 py-2 text-sm border border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
            <option value="">All Types</option>
            <option value="sync">Sync</option>
            <option value="export">Export</option>
        </select>
    </div>
    {{ btn("Refresh", variant="secondary", size="sm", onclick="loadJobs()") }}
</div>

{# Jobs Table #}
{% call table(headers=["ID", "Type", "Status", "Priority", "Attempts", "Created", "Actions"]) %}
<tbody id="jobsTable">
    <tr>
        <td colspan="7" class="text-center py-8 text-slate-500 dark:text-slate-400">Loading...</td>
    </tr>
</tbody>
{% endcall %}
{% endcall %}

{# Job Detail Modal #}
{% call modal(id="detailModal", title="Job Details", size="lg") %}
<dl id="jobDetail" class="space-y-3">
    {# Populated by JavaScript #}
</dl>
{% endcall %}

{% endblock %}

{% block scripts %}
<script>
    let autoRefreshInterval = null;

    function showAlert(message, type) {
        const container = document.getElementById('alertContainer');
        const alertClass = type === 'success'
            ? 'bg-green-50 dark:bg-green-900/30 border-green-200 dark:border-green-800 text-green-800 dark:text-green-300'
            : 'bg-red-50 dark:bg-red-900/30 border-red-200 dark:border-red-800 text-red-800 dark:text-red-300';
        container.innerHTML = `<div class="p-4 rounded-md border mb-4 ${alertClass}" role="alert">
            <p class="text-sm">${message}</p>
        </div>`;
        setTimeout(() => { container.innerHTML = ''; }, 5000);
    }

    function formatDate(isoString) {
        if (!isoString) return '-';
        return new Date(isoString).toLocaleString();
    }

    async function loadStats() {
        try {
            const response = await fetch('/api/jobs/stats');
            const data = await response.json();

            if (data.success) {
                document.getElementById('statPending').textContent = data.pending;
                document.getElementById('statRunning').textContent = data.running;
                document.getElementById('statCompleted').textContent = data.completed;
                document.getElementById('statFailed').textContent = data.failed;
                document.getElementById('statTotal').textContent = data.total;
            }
        } catch (error) {
            console.error('Failed to load stats:', error);
        }
    }

    function getStatusBadgeClasses(status) {
        const variants = {
            'pending': 'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300',
            'running': 'bg-blue-100 text-blue-800 dark:bg-blue-900/50 dark:text-blue-300',
            'completed': 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300',
            'failed': 'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300',
            'cancelled': 'bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-300'
        };
        return variants[status] || variants['cancelled'];
    }

    async function loadJobs() {
        const status = document.getElementById('statusFilter').value;
        const type = document.getElementById('typeFilter').value;

        let url = '/api/jobs?limit=50';
        if (status) url += `&status=${status}`;
        if (type) url += `&job_type=${type}`;

        try {
            const response = await fetch(url);
            const data = await response.json();

            const tbody = document.getElementById('jobsTable');

            if (!data.success || !data.jobs || data.jobs.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center py-8 text-slate-500 dark:text-slate-400">No jobs found</td></tr>';
                return;
            }

            tbody.innerHTML = data.jobs.map(job => `
                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50">
                    <td class="px-4 py-3">${job.id}</td>
                    <td class="px-4 py-3">${job.job_type}</td>
                    <td class="px-4 py-3"><span class="inline-flex items-center px-2.5 py-1 text-xs font-semibold rounded-full ${getStatusBadgeClasses(job.status)}">${job.status}</span></td>
                    <td class="px-4 py-3">${job.priority}</td>
                    <td class="px-4 py-3">${job.attempts}/${job.max_attempts}</td>
                    <td class="px-4 py-3 text-slate-500 dark:text-slate-400">${formatDate(job.created_at)}</td>
                    <td class="px-4 py-3">
                        <div class="flex gap-2">
                            <button onclick="viewJob(${job.id})" class="px-2.5 py-1.5 text-xs font-medium rounded-md bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-200 border border-slate-300 dark:border-slate-600 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors">View</button>
                            ${job.status === 'pending' ? `<button onclick="cancelJob(${job.id})" class="px-2.5 py-1.5 text-xs font-medium rounded-md bg-red-600 text-white hover:bg-red-700 transition-colors">Cancel</button>` : ''}
                            ${job.status === 'failed' ? `<button onclick="retryJob(${job.id})" class="px-2.5 py-1.5 text-xs font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 transition-colors">Retry</button>` : ''}
                        </div>
                    </td>
                </tr>
            `).join('');

        } catch (error) {
            console.error('Failed to load jobs:', error);
            showAlert('Failed to load jobs: ' + error.message, 'error');
        }
    }

    async function viewJob(id) {
        try {
            const response = await fetch(`/api/jobs/${id}`);
            const data = await response.json();

            if (!data.success) {
                showAlert('Job not found', 'error');
                return;
            }

            const job = data.job;
            const detail = document.getElementById('jobDetail');
            detail.innerHTML = `
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Job ID</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${job.id}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Type</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${job.job_type}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Status</span>
                    <span class="inline-flex items-center px-2.5 py-1 text-xs font-semibold rounded-full ${getStatusBadgeClasses(job.status)}">${job.status}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Priority</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${job.priority}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Attempts</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${job.attempts}/${job.max_attempts}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Created</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${formatDate(job.created_at)}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Started</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${formatDate(job.started_at)}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400">Completed</span>
                    <span class="text-sm font-medium text-slate-900 dark:text-white">${formatDate(job.completed_at)}</span>
                </div>
                ${job.error ? `<div class="py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400 block mb-1">Error</span>
                    <span class="text-sm text-red-600 dark:text-red-400">${job.error}</span>
                </div>` : ''}
                <div class="py-2 border-b border-slate-200 dark:border-slate-700">
                    <span class="text-sm text-slate-500 dark:text-slate-400 block mb-2">Payload</span>
                    <pre class="bg-slate-100 dark:bg-slate-900 text-slate-800 dark:text-slate-200 p-3 rounded-md text-xs font-mono overflow-x-auto">${JSON.stringify(job.payload, null, 2)}</pre>
                </div>
                ${job.result ? `<div class="py-2">
                    <span class="text-sm text-slate-500 dark:text-slate-400 block mb-2">Result</span>
                    <pre class="bg-slate-100 dark:bg-slate-900 text-slate-800 dark:text-slate-200 p-3 rounded-md text-xs font-mono overflow-x-auto">${JSON.stringify(job.result, null, 2)}</pre>
                </div>` : ''}
            `;

            openModal('detailModal');

        } catch (error) {
            showAlert('Failed to load job: ' + error.message, 'error');
        }
    }

    async function cancelJob(id) {
        if (!confirm('Cancel this job?')) return;

        try {
            const response = await fetch(`/api/jobs/${id}/cancel`, { method: 'POST' });
            const data = await response.json();

            if (data.success) {
                showAlert('Job cancelled', 'success');
                loadJobs();
                loadStats();
            } else {
                showAlert(data.error || 'Failed to cancel job', 'error');
            }
        } catch (error) {
            showAlert('Failed to cancel job: ' + error.message, 'error');
        }
    }

    async function retryJob(id) {
        if (!confirm('Retry this job?')) return;

        try {
            const response = await fetch(`/api/jobs/${id}/retry`, { method: 'POST' });
            const data = await response.json();

            if (data.success) {
                showAlert('Job requeued', 'success');
                loadJobs();
                loadStats();
            } else {
                showAlert(data.error || 'Failed to retry job', 'error');
            }
        } catch (error) {
            showAlert('Failed to retry job: ' + error.message, 'error');
        }
    }

    function openModal(id) {
        const modal = document.getElementById(id);
        if (modal) {
            modal.classList.remove('hidden');
        }
    }

    function closeModal(id) {
        const modal = document.getElementById(id);
        if (modal) {
            modal.classList.add('hidden');
        }
    }

    function toggleAutoRefresh() {
        const toggle = document.getElementById('autoRefreshToggle');

        if (toggle.checked) {
            autoRefreshInterval = setInterval(() => {
                loadJobs();
                loadStats();
            }, 5000);
        } else {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
            }
        }
    }

    // Close modal on outside click
    document.getElementById('detailModal').addEventListener('click', function(e) {
        if (e.target === this || e.target.classList.contains('bg-black/50')) {
            closeModal('detailModal');
        }
    });

    // Close modal on Escape
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal('detailModal');
    });

    // Initial load
    loadJobs();
    loadStats();
</script>
{% endblock %}
