/**
 * ConnectionsSection — personal extension connection CRUD
 * v0.38.1: Scoped credential management for extensions
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

function esc(s) { return s == null ? '' : String(s); }

export function ConnectionsSection() {
    const [connections, setConnections] = useState(null);
    const [connTypes, setConnTypes] = useState([]);
    const [showForm, setShowForm] = useState(false);
    const [editId, setEditId] = useState(null);
    const [form, setForm] = useState({ type: '', package_id: '', name: '', config: {} });
    const [saving, setSaving] = useState(false);

    const load = useCallback(async () => {
        try {
            const resp = await sw.api.connections.list();
            setConnections(resp || []);
        } catch (e) {
            setConnections([]);
        }
    }, []);

    const loadTypes = useCallback(async () => {
        try {
            const types = await sw.api.connectionTypes.list();
            setConnTypes((types || []).map(ct => ({
                type: ct.type, label: ct.label || ct.type,
                packageId: ct.package_id, fields: ct.fields || {}
            })));
        } catch (_) {}
    }, []);

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

    const selectedType = connTypes.find(t => t.type === form.type);

    const openAdd = useCallback(() => {
        setEditId(null);
        setForm({ type: connTypes[0]?.type || '', package_id: connTypes[0]?.packageId || '', name: '', config: {} });
        setShowForm(true);
    }, [connTypes]);

    const openEdit = useCallback((conn) => {
        setEditId(conn.id);
        setForm({ type: conn.type, package_id: conn.package_id, name: conn.name, config: {} });
        setShowForm(true);
    }, []);

    const cancel = useCallback(() => {
        setShowForm(false);
        setEditId(null);
    }, []);

    const save = useCallback(async () => {
        if (!form.type || !form.name) {
            sw.emit('toast', { message: 'Type and name are required', variant: 'error' });
            return;
        }
        setSaving(true);
        try {
            if (editId) {
                const patch = { name: form.name };
                if (Object.keys(form.config).length > 0) patch.config = form.config;
                await sw.api.connections.update(editId, patch);
                sw.emit('toast', { message: 'Connection updated', variant: 'success' });
            } else {
                await sw.api.connections.create({
                    type: form.type, package_id: form.package_id,
                    name: form.name, config: form.config,
                });
                sw.emit('toast', { message: 'Connection created', variant: 'success' });
            }
            setShowForm(false);
            setEditId(null);
            load();
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        } finally {
            setSaving(false);
        }
    }, [form, editId, load]);

    const del = useCallback(async (conn) => {
        const ok = await sw.confirm(`Remove connection "${conn.name}"?`);
        if (!ok) return;
        try {
            await sw.api.connections.del(conn.id);
            sw.emit('toast', { message: 'Connection removed', variant: 'success' });
            load();
        } catch (e) {
            sw.emit('toast', { message: e.message, variant: 'error' });
        }
    }, [load]);

    const setField = useCallback((key, val) => {
        setForm(f => ({ ...f, [key]: val }));
    }, []);

    const setConfigField = useCallback((key, val) => {
        setForm(f => ({ ...f, config: { ...f.config, [key]: val } }));
    }, []);

    const onTypeChange = useCallback((typeVal) => {
        const ct = connTypes.find(t => t.type === typeVal);
        setForm(f => ({ ...f, type: typeVal, package_id: ct?.packageId || f.package_id, config: {} }));
    }, [connTypes]);

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

    return html`
        <div style="margin-bottom:12px;">
            <button class="btn-md btn-primary" onClick=${openAdd}
                    disabled=${!connTypes.length}>+ Add Connection</button>
            ${!connTypes.length && html`
                <span style="margin-left:8px;color:var(--text-3);font-size:12px;">
                    No installed packages declare connection types.
                </span>
            `}
        </div>

        ${showForm && html`
            <div class="settings-section" style="margin-bottom:16px;">
                <h3>${editId ? 'Edit Connection' : 'Add Connection'}</h3>
                ${!editId && html`
                    <div class="form-group">
                        <label>Connection Type</label>
                        <select value=${form.type}
                                onChange=${e => onTypeChange(e.target.value)}>
                            ${connTypes.map(ct => html`
                                <option value=${ct.type}>${esc(ct.label)}</option>
                            `)}
                        </select>
                    </div>
                `}
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" placeholder="e.g. Work Gitea"
                           value=${form.name}
                           onInput=${e => setField('name', e.target.value)} />
                </div>
                ${selectedType && Object.entries(selectedType.fields || {}).map(([fk, fd]) => html`
                    <div class="form-group" key=${fk}>
                        <label>${esc(fd.label || fk)}${fd.required ? ' *' : ''}${editId && fd.type === 'secret' ? ' (leave blank to keep current)' : ''}</label>
                        ${fd.type === 'secret' ? html`
                            <input type="password" placeholder="\u2022\u2022\u2022\u2022"
                                   value=${form.config[fk] || ''}
                                   onInput=${e => setConfigField(fk, e.target.value)} />
                        ` : fd.type === 'url' ? html`
                            <input type="url" placeholder="https://..."
                                   value=${form.config[fk] || ''}
                                   onInput=${e => setConfigField(fk, e.target.value)} />
                        ` : fd.type === 'boolean' ? html`
                            <input type="checkbox" checked=${!!form.config[fk]}
                                   onChange=${e => setConfigField(fk, e.target.checked)} />
                        ` : fd.type === 'number' ? html`
                            <input type="number"
                                   value=${form.config[fk] || ''}
                                   onInput=${e => setConfigField(fk, e.target.value)} />
                        ` : html`
                            <input type="text"
                                   value=${form.config[fk] || ''}
                                   onInput=${e => setConfigField(fk, e.target.value)} />
                        `}
                    </div>
                `)}
                <div style="display:flex;gap:8px;margin-top:12px;">
                    <button class="btn-md btn-primary" disabled=${saving}
                            onClick=${save}>
                        ${saving ? 'Saving\u2026' : editId ? 'Update' : 'Add'}
                    </button>
                    <button class="btn-md btn-secondary" onClick=${cancel}>Cancel</button>
                </div>
            </div>
        `}

        ${!connections.length && !showForm && html`
            <div class="empty-hint">No connections configured.</div>
        `}

        ${connections.length > 0 && html`
            <table class="admin-table">
                <thead><tr><th>Name</th><th>Type</th><th>Scope</th><th>Status</th><th></th></tr></thead>
                <tbody>
                    ${connections.map(c => html`
                        <tr>
                            <td style="font-weight:500;font-size:13px;">${esc(c.name)}</td>
                            <td style="font-size:12px;color:var(--text-2);">${esc(c.type)}</td>
                            <td style="font-size:11px;">
                                <span class="badge" style=${
                                    c.scope === 'global' ? 'background:var(--accent);color:#fff;' :
                                    c.scope === 'team' ? 'background:var(--green);color:#fff;' :
                                    ''
                                }>${esc(c.scope || 'personal')}</span>
                            </td>
                            <td style="font-size:12px;">
                                ${c.is_active
                                    ? html`<span style="color:var(--green);">\u25CF Active</span>`
                                    : html`<span style="color:var(--text-3);">\u25CB Inactive</span>`}
                            </td>
                            <td class="admin-actions-cell" style="white-space:nowrap;">
                                ${c.scope === 'personal' ? html`
                                    <button class="icon-btn" title="Edit" onClick=${() => openEdit(c)}>
                                        \u{270F}\u{FE0F}
                                    </button>
                                    <button class="icon-btn icon-btn-danger" title="Delete"
                                            onClick=${() => del(c)}>
                                        \u{1F5D1}
                                    </button>
                                ` : ''}
                            </td>
                        </tr>
                    `)}
                </tbody>
            </table>
        `}
    `;
}
