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

export default function KnowledgeSection() {
    const [kbs, setKbs] = useState([]);
    const [loading, setLoading] = useState(true);
    const [detail, setDetail] = useState(null);
    const [docs, setDocs] = useState([]);

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

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

    async function openDetail(kb) {
        setDetail(kb);
        try {
            const d = await sw.api.knowledge.documents(kb.id);
            setDocs(d.data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function uploadDoc() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.txt,.md,.csv,.html';
        input.onchange = async () => {
            const file = input.files[0];
            if (!file) return;
            try {
                await sw.api.knowledge.upload(detail.id, file);
                sw.toast('Document uploaded', 'success');
                const d = await sw.api.knowledge.documents(detail.id);
                setDocs(d.data || []);
            } catch (e) { sw.toast(e.message, 'error'); }
        };
        input.click();
    }

    async function deleteDoc(docId) {
        const ok = await sw.confirm('Delete this document?', true);
        if (!ok) return;
        try {
            await sw.api.knowledge.delDoc(detail.id, docId);
            sw.toast('Document deleted', 'success');
            setDocs(prev => prev.filter(d => d.id !== docId));
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deleteKb(id) {
        const ok = await sw.confirm('Delete this knowledge base and all documents?', true);
        if (!ok) return;
        try {
            await sw.api.knowledge.del(id);
            sw.toast('Knowledge base deleted', 'success');
            setDetail(null);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    function statusBadge(status) {
        const cls = status === 'ready' ? 'badge-active' : status === 'error' ? 'badge-inactive' : 'badge-pending';
        return html`<span class="badge ${cls}">${status}</span>`;
    }

    function formatBytes(b) {
        if (!b) return '0 B';
        if (b < 1024) return b + ' B';
        if (b < 1048576) return (b / 1024).toFixed(1) + ' KB';
        return (b / 1048576).toFixed(1) + ' MB';
    }

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

    if (detail) return html`
        <div>
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <button class="btn-small" onClick=${() => setDetail(null)}>\u2190 Back</button>
                <h4 style="margin:0;">${detail.name}</h4>
                ${statusBadge(detail.status || 'active')}
                <div style="flex:1"></div>
                <button class="btn-small" onClick=${uploadDoc}>Upload Document</button>
                <button class="btn-small btn-danger" onClick=${() => deleteKb(detail.id)}>Delete KB</button>
            </div>

            <p class="text-muted" style="font-size:12px;margin-bottom:12px;">
                ${detail.document_count || 0} docs \u2022 ${detail.chunk_count || 0} chunks \u2022 ${formatBytes(detail.total_bytes)}
                \u2022 scope: ${detail.scope || 'personal'}
            </p>

            <div class="admin-list">
                ${docs.length === 0 && html`<div class="empty-hint">No documents</div>`}
                ${docs.map(d => html`
                    <div class="admin-surface-row" key=${d.id}>
                        <div style="flex:1;min-width:0;">
                            <strong>${d.filename}</strong>
                            <span class="text-muted" style="margin-left:8px;font-size:11px;">${formatBytes(d.size_bytes)}</span>
                            ${' '}${statusBadge(d.status || 'pending')}
                        </div>
                        <button class="btn-small btn-danger" onClick=${() => deleteDoc(d.id)}>Delete</button>
                    </div>
                `)}
            </div>
        </div>
    `;

    return html`
        <div>
            <div class="admin-list">
                ${kbs.length === 0 && html`<div class="empty-hint">No knowledge bases</div>`}
                ${kbs.map(k => html`
                    <div class="admin-surface-row" key=${k.id} style="cursor:pointer;" onClick=${() => openDetail(k)}>
                        <div style="flex:1;min-width:0;">
                            <strong>${k.name}</strong>
                            <span class="text-muted" style="margin-left:8px;font-size:12px;">${k.document_count || 0} docs</span>
                        </div>
                        <span class="badge">${k.scope || 'personal'}</span>
                        ${statusBadge(k.status || 'active')}
                    </div>
                `)}
            </div>
        </div>
    `;
}
