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

export default function TasksSection({ teamId }) {
    const [tasks, setTasks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showCreate, setShowCreate] = useState(false);

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

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

    async function createTask(e) {
        e.preventDefault();
        const form = e.target;
        try {
            await sw.api.teams.createTask(teamId, {
                name: form.name.value.trim(),
                schedule: form.schedule.value.trim(),
                description: form.description.value.trim(),
            });
            sw.toast('Task created', 'success');
            setShowCreate(false);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    async function killTask(id) {
        try {
            await sw.api.teams.killTask(teamId, 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.teams.deleteTask(teamId, id);
            sw.toast('Task deleted', 'success');
            load();
        } 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 style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <div style="flex:1"></div>
                <button class="btn-md btn-primary" onClick=${() => setShowCreate(true)}>+ Add</button>
            </div>

            ${showCreate && html`
                <form class="admin-inline-form" style="margin-bottom:16px;" onSubmit=${createTask}>
                    <div class="form-row">
                        <div class="form-group"><label>Name</label><input name="name" placeholder="Daily Sync" /></div>
                        <div class="form-group"><label>Schedule</label><input name="schedule" placeholder="0 9 * * *" /></div>
                    </div>
                    <div class="form-group"><label>Description</label><input name="description" placeholder="Optional" /></div>
                    <div class="form-row" style="margin-top:8px;gap:8px;">
                        <button type="submit" class="btn-small btn-primary">Create</button>
                        <button type="button" class="btn-small" onClick=${() => setShowCreate(false)}>Cancel</button>
                    </div>
                </form>
            `}

            <div class="admin-list">
                ${tasks.length === 0 && html`<div class="empty-hint">No tasks</div>`}
                ${tasks.map(t => html`
                    <div class="admin-surface-row" key=${t.id}>
                        <div style="flex:1;min-width:0;">
                            <strong>${t.name}</strong>
                            ${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 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>
                `)}
            </div>
        </div>
    `;
}
