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

export default function ModelsSection() {
    const [models, setModels] = useState([]);
    const [search, setSearch] = useState('');
    const [loading, setLoading] = useState(true);
    const [fetching, setFetching] = useState(false);

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

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

    async function fetchModels() {
        setFetching(true);
        try {
            const result = await sw.api.admin.models.fetch();
            sw.toast(`Synced: ${result.added || 0} added, ${result.updated || 0} updated, ${result.total || 0} total`, 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setFetching(false); }
    }

    async function setVisibility(id, visibility) {
        try {
            await sw.api.admin.models.update(id, { visibility });
            setModels(prev => prev.map(m => m.id === id ? { ...m, visibility } : m));
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function bulkSetVisibility(visibility) {
        try {
            await sw.api.admin.models.bulkUpdate(visibility);
            sw.toast(`All models set to ${visibility}`, 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    const filtered = models.filter(m => {
        if (!search) return true;
        const q = search.toLowerCase();
        return (m.model_id || m.id || '').toLowerCase().includes(q) ||
               (m.display_name || '').toLowerCase().includes(q) ||
               (m.provider_name || '').toLowerCase().includes(q);
    });

    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;">
                <button class="btn-small btn-primary" onClick=${fetchModels} disabled=${fetching}>
                    ${fetching ? 'Fetching\u2026' : 'Fetch Models'}
                </button>
                <span class="text-muted" style="font-size:12px;">${models.length} models</span>
                <div style="flex:1"></div>
                <button class="btn-small" onClick=${() => bulkSetVisibility('enabled')}>Enable All</button>
                <button class="btn-small" onClick=${() => bulkSetVisibility('disabled')}>Disable All</button>
            </div>

            <div class="admin-search" style="margin-bottom:12px;">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color:var(--text-3);flex-shrink:0;"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                <input placeholder="Search models\u2026" value=${search} onInput=${e => setSearch(e.target.value)} autocomplete="off" />
            </div>

            <div class="admin-list">
                ${filtered.length === 0 && html`<div class="empty-hint">No models found</div>`}
                ${filtered.map(m => html`
                    <div class="admin-surface-row" key=${m.id}>
                        <div style="flex:1;min-width:0;">
                            <strong>${m.display_name || m.model_id || m.id}</strong>
                            ${m.display_name && m.model_id && html`<span class="text-muted" style="margin-left:8px;font-size:11px;">${m.model_id}</span>`}
                            ${m.provider_name && html`<span class="badge" style="margin-left:6px;">${m.provider_name}</span>`}
                        </div>
                        <select value=${m.visibility || 'disabled'} onChange=${e => setVisibility(m.id, e.target.value)}
                                style="font-size:11px;padding:2px 4px;">
                            <option value="enabled">enabled</option>
                            <option value="disabled">disabled</option>
                            <option value="team">team only</option>
                        </select>
                    </div>
                `)}
            </div>
        </div>
    `;
}
