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

const STAGE_MODES = ['form', 'review', 'delegated', 'automated'];
const ENTRY_MODES = ['public_link', 'team_only'];

export default function WorkflowsSection() {
    const [workflows, setWorkflows] = useState([]);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState(null); // null | 'new' | workflow
    const [stages, setStages] = useState([]);
    const [showCreate, setShowCreate] = useState(false);

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

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

    async function openEdit(wf) {
        setEditing(wf);
        try {
            const detail = await sw.api.workflows.get(wf.id);
            setStages(detail.stages || []);
        } catch (e) { sw.toast(e.message, 'error'); setStages([]); }
    }

    async function createWorkflow(e) {
        e.preventDefault();
        const form = e.target;
        try {
            await sw.api.workflows.create({
                name: form.name.value.trim(),
                slug: form.slug.value.trim(),
                entry_mode: form.entry_mode.value,
                description: form.description.value.trim(),
            });
            sw.toast('Workflow created', 'success');
            setShowCreate(false);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function updateWorkflow(e) {
        e.preventDefault();
        const form = e.target;
        try {
            await sw.api.workflows.update(editing.id, {
                name: form.name.value.trim(),
                description: form.description.value.trim(),
                entry_mode: form.entry_mode.value,
                is_active: form.is_active.checked,
            });
            sw.toast('Workflow updated', 'success');
            setEditing(null);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deleteWorkflow(id) {
        const ok = await sw.confirm('Delete this workflow? All stages, versions, and instances will be deleted.', true);
        if (!ok) return;
        try {
            await sw.api.workflows.del(id);
            sw.toast('Workflow deleted', 'success');
            setEditing(null);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    if (editing) return html`
        <form onSubmit=${updateWorkflow}>
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <button type="button" class="btn-small" onClick=${() => setEditing(null)}>\u2190 Back</button>
                <h4 style="margin:0;">Edit: ${editing.name}</h4>
                <div style="flex:1"></div>
                <button type="button" class="btn-small btn-danger" onClick=${() => deleteWorkflow(editing.id)}>Delete</button>
            </div>
            <div class="form-row">
                <div class="form-group"><label>Name</label><input name="name" value=${editing.name || ''} /></div>
                <div class="form-group"><label>Entry Mode</label>
                    <select name="entry_mode">
                        ${ENTRY_MODES.map(m => html`<option key=${m} value=${m} selected=${editing.entry_mode === m}>${m}</option>`)}
                    </select>
                </div>
            </div>
            <div class="form-group"><label>Description</label><input name="description" value=${editing.description || ''} /></div>
            <label class="toggle-label" style="margin:8px 0;">
                <input type="checkbox" name="is_active" checked=${editing.is_active !== false} />
                <span class="toggle-track"></span><span>Active</span>
            </label>

            <h5 style="margin:16px 0 8px;">Stages (${stages.length})</h5>
            <div class="admin-list">
                ${stages.map((s, i) => html`
                    <div class="admin-surface-row" key=${s.id}>
                        <span class="text-muted" style="font-size:11px;width:24px;">#${i + 1}</span>
                        <strong style="flex:1;">${s.name || `Stage ${i + 1}`}</strong>
                        <span class="badge">${s.stage_mode}</span>
                        <span class="badge">${s.audience || 'team'}</span>
                    </div>
                `)}
                ${stages.length === 0 && html`<div class="empty-hint">No stages defined</div>`}
            </div>

            <div class="form-row" style="margin-top:16px;gap:8px;">
                <button type="submit" class="btn-small btn-primary">Save</button>
            </div>
        </form>
    `;

    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=${createWorkflow}>
                    <div class="form-row">
                        <div class="form-group"><label>Name</label><input name="name" placeholder="Customer Intake" /></div>
                        <div class="form-group"><label>Slug</label><input name="slug" placeholder="customer-intake" /></div>
                        <div class="form-group"><label>Entry Mode</label>
                            <select name="entry_mode">
                                ${ENTRY_MODES.map(m => html`<option key=${m} value=${m}>${m}</option>`)}
                            </select>
                        </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">
                ${workflows.length === 0 && html`<div class="empty-hint">No workflows</div>`}
                ${workflows.map(w => html`
                    <div class="admin-surface-row" key=${w.id} style="cursor:pointer;" onClick=${() => openEdit(w)}>
                        <div style="flex:1;min-width:0;">
                            <strong>${w.name}</strong>
                            <span class="text-muted" style="margin-left:8px;font-size:11px;">/${w.slug}</span>
                        </div>
                        <span class="badge">${w.entry_mode}</span>
                        <span class="badge ${w.is_active ? 'badge-active' : 'badge-inactive'}">${w.is_active ? 'active' : 'inactive'}</span>
                        <span class="text-muted" style="font-size:11px;">v${w.version || 0}</span>
                    </div>
                `)}
            </div>
        </div>
    `;
}
