/**
 * Admin > Workflows > Tasks
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function TasksSection() {
    const [tasks, setTasks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [expandedRuns, setExpandedRuns] = useState({}); // taskId → runs[]

    const load = useCallback(async () => {
        try {
            const data = await sw.api.admin.tasks.list();
            setTasks(data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => { load(); }, []);

    async function runTask(id) {
        try {
            await sw.api.admin.tasks.run(id);
            sw.toast('Task triggered', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function killTask(id) {
        try {
            await sw.api.admin.tasks.kill(id);
            sw.toast('Task cancelled', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deleteTask(id) {
        const ok = await sw.confirm('Delete this task?', true);
        if (!ok) return;
        try {
            await sw.api.admin.tasks.del(id);
            sw.toast('Task deleted', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function toggleRuns(taskId) {
        if (expandedRuns[taskId]) {
            setExpandedRuns(prev => { const n = { ...prev }; delete n[taskId]; return n; });
            return;
        }
        try {
            const data = await sw.api.tasks.runs(taskId);
            const runs = data || [];
            setExpandedRuns(prev => ({ ...prev, [taskId]: runs }));
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    function fmtDate(d) {
        if (!d) return '\u2014';
        return new Date(d).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' });
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div>
            <div class="admin-list">
                ${tasks.length === 0 && html`<div class="empty-hint">No tasks</div>`}
                ${tasks.map(t => html`
                    <div key=${t.id}>
                        <div class="admin-surface-row">
                            <div style="flex:1;min-width:0;">
                                <strong>${t.name}</strong>
                                <span class="text-muted" style="margin-left:8px;font-size:11px;">${t.scope || 'personal'}</span>
                                ${t.schedule && html`<span class="badge" style="margin-left:6px;">${t.schedule}</span>`}
                            </div>
                            <span class="text-muted" style="font-size:11px;">
                                last: ${fmtDate(t.last_run_at)} \u2022 next: ${fmtDate(t.next_run_at)}
                            </span>
                            <span class="badge ${t.is_active ? 'badge-active' : 'badge-inactive'}">${t.is_active ? 'active' : 'paused'}</span>
                            <div class="admin-actions-cell">
                                <button class="btn-small" onClick=${() => toggleRuns(t.id)}>${expandedRuns[t.id] ? 'Hide Runs' : 'Runs'}</button>
                                <button class="btn-small btn-primary" onClick=${() => runTask(t.id)}>Run</button>
                                <button class="btn-small" onClick=${() => killTask(t.id)}>Kill</button>
                                <button class="btn-small btn-danger" onClick=${() => deleteTask(t.id)}>Delete</button>
                            </div>
                        </div>
                        ${expandedRuns[t.id] && html`
                            <div style="padding:4px 0 8px 24px;">
                                ${expandedRuns[t.id].length === 0 && html`<span class="text-muted" style="font-size:12px;">No runs</span>`}
                                ${expandedRuns[t.id].map(r => html`
                                    <div key=${r.id} style="font-size:12px;display:flex;gap:8px;padding:2px 0;">
                                        <span class="badge ${r.status === 'completed' ? 'badge-active' : r.status === 'failed' ? 'badge-inactive' : 'badge-pending'}">${r.status}</span>
                                        <span>${fmtDate(r.started_at)}</span>
                                        <span class="text-muted">${r.tokens_used || 0} tokens</span>
                                        ${r.error && html`<span style="color:var(--danger);">${r.error}</span>`}
                                    </div>
                                `)}
                            </div>
                        `}
                    </div>
                `)}
            </div>
        </div>
    `;
}
