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

export default function PersonasSection() {
    const [personas, setPersonas] = useState([]);
    const [models, setModels] = useState([]);
    const [kbs, setKbs] = useState([]);
    const [search, setSearch] = useState('');
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState(null); // null | 'new' | persona object
    const [editKbs, setEditKbs] = useState([]);
    const [editToolGrants, setEditToolGrants] = useState([]);

    const load = useCallback(async () => {
        try {
            const [p, m, k] = await Promise.all([
                sw.api.admin.personas.list(),
                sw.api.admin.models.list().catch(() => []),
                sw.api.knowledge.list().catch(() => []),
            ]);
            setPersonas(p || []);
            setModels(m || []);
            setKbs(k.data || []);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    async function startEdit(persona) {
        setEditing(persona);
        if (persona !== 'new') {
            try {
                const [kbData, tgData] = await Promise.all([
                    sw.api.admin.personas.kbs(persona.id).catch(() => []),
                    sw.api.admin.personas.toolGrants(persona.id).catch(() => ({ tool_names: [] })),
                ]);
                setEditKbs(Array.isArray(kbData) ? kbData.map(k => k.kb_id || k.id) : kbData.kb_ids || []);
                setEditToolGrants(tgData.tool_names || []);
            } catch { setEditKbs([]); setEditToolGrants([]); }
        } else {
            setEditKbs([]);
            setEditToolGrants([]);
        }
    }

    async function savePersona(e) {
        e.preventDefault();
        const form = e.target;
        const data = {
            name: form.pname.value.trim(),
            handle: form.handle.value.trim(),
            description: form.description.value.trim(),
            icon: form.icon.value.trim(),
            system_prompt: form.system_prompt.value,
            base_model_id: form.model.value || null,
            temperature: form.temperature.value ? parseFloat(form.temperature.value) : null,
            max_tokens: form.max_tokens.value ? parseInt(form.max_tokens.value) : null,
            memory_enabled: form.memory_enabled.checked,
        };
        try {
            let id;
            if (editing === 'new') {
                const res = await sw.api.admin.personas.create(data);
                id = res.id;
                sw.toast('Persona created', 'success');
            } else {
                id = editing.id;
                await sw.api.admin.personas.update(id, data);
                sw.toast('Persona updated', 'success');
            }
            // Save KB bindings
            if (id) {
                await sw.api.admin.personas.setKbs(id, { kb_ids: editKbs }).catch(() => {});
                await sw.api.admin.personas.setToolGrants(id, { tool_names: editToolGrants }).catch(() => {});
            }
            setEditing(null);
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function deletePersona(id) {
        const ok = await sw.confirm('Delete this persona?', true);
        if (!ok) return;
        try {
            await sw.api.admin.personas.del(id);
            sw.toast('Persona deleted', 'success');
            load();
        } catch (e) { sw.toast(e.message, 'error'); }
    }

    async function uploadAvatar(id) {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = async () => {
            const file = input.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = async () => {
                try {
                    await sw.api.admin.personas.avatar(id, reader.result);
                    sw.toast('Avatar uploaded', 'success');
                    load();
                } catch (e) { sw.toast(e.message, 'error'); }
            };
            reader.readAsDataURL(file);
        };
        input.click();
    }

    function toggleKb(kbId) {
        setEditKbs(prev => prev.includes(kbId) ? prev.filter(k => k !== kbId) : [...prev, kbId]);
    }

    const filtered = personas.filter(p => {
        if (!search) return true;
        const q = search.toLowerCase();
        return (p.name || '').toLowerCase().includes(q) || (p.handle || '').toLowerCase().includes(q);
    });

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

    if (editing) {
        const isNew = editing === 'new';
        const p = isNew ? {} : editing;
        return html`
            <form onSubmit=${savePersona}>
                <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;">${isNew ? 'Create Persona' : `Edit: ${p.name}`}</h4>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Name</label><input name="pname" value=${p.name || ''} placeholder="Code Reviewer" /></div>
                    <div class="form-group"><label>Handle</label><input name="handle" value=${p.handle || ''} placeholder="code-reviewer" /></div>
                    <div class="form-group" style="width:60px;"><label>Icon</label><input name="icon" value=${p.icon || ''} placeholder="\ud83d\udd0d" /></div>
                </div>
                <div class="form-group"><label>Description</label><input name="description" value=${p.description || ''} placeholder="Optional description" /></div>
                <div class="form-group"><label>System Prompt</label>
                    <textarea name="system_prompt" rows="4" placeholder="System prompt\u2026">${p.system_prompt || ''}</textarea>
                </div>
                <div class="form-row">
                    <div class="form-group"><label>Model</label>
                        <select name="model">
                            <option value="">Default</option>
                            ${models.map(m => html`<option key=${m.id} value=${m.model_id || m.id} selected=${p.base_model_id === (m.model_id || m.id)}>${m.display_name || m.model_id || m.id}</option>`)}
                        </select>
                    </div>
                    <div class="form-group" style="width:100px;"><label>Temperature</label>
                        <input name="temperature" type="number" step="0.1" min="0" max="2" value=${p.temperature ?? ''} placeholder="0.7" />
                    </div>
                    <div class="form-group" style="width:100px;"><label>Max Tokens</label>
                        <input name="max_tokens" type="number" min="1" value=${p.max_tokens ?? ''} placeholder="4096" />
                    </div>
                </div>
                <label class="toggle-label" style="margin:8px 0;">
                    <input type="checkbox" name="memory_enabled" checked=${!!p.memory_enabled} />
                    <span class="toggle-track"></span>
                    <span>Memory enabled</span>
                </label>

                ${!isNew && html`
                    <div style="margin:12px 0;">
                        <button type="button" class="btn-small" onClick=${() => uploadAvatar(p.id)}>Upload Avatar</button>
                        ${p.avatar && html`<button type="button" class="btn-small btn-danger" style="margin-left:6px;"
                            onClick=${async () => { await sw.api.admin.personas.delAvatar(p.id); sw.toast('Avatar removed', 'success'); load(); }}>Remove Avatar</button>`}
                    </div>
                `}

                <div class="settings-section" style="margin:12px 0;">
                    <h5 style="margin:0 0 8px;">Knowledge Base Bindings</h5>
                    ${kbs.length === 0
                        ? html`<span class="text-muted" style="font-size:12px;">No knowledge bases available</span>`
                        : kbs.map(k => html`
                            <label class="toggle-label" key=${k.id}>
                                <input type="checkbox" checked=${editKbs.includes(k.id)} onChange=${() => toggleKb(k.id)} />
                                <span class="toggle-track"></span>
                                <span>${k.name}</span>
                            </label>
                        `)
                    }
                </div>

                <div class="form-row" style="margin-top:16px;gap:8px;">
                    <button type="submit" class="btn-small btn-primary">${isNew ? 'Create' : 'Save'}</button>
                    <button type="button" class="btn-small" onClick=${() => setEditing(null)}>Cancel</button>
                </div>
            </form>
        `;
    }

    return html`
        <div>
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                <div class="admin-search">
                    <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 personas\u2026" value=${search} onInput=${e => setSearch(e.target.value)} autocomplete="off" />
                </div>
                <div style="flex:1"></div>
                <button class="btn-md btn-primary" onClick=${() => startEdit('new')}>+ Add</button>
            </div>

            <div class="admin-list">
                ${filtered.length === 0 && html`<div class="empty-hint">No personas</div>`}
                ${filtered.map(p => html`
                    <div class="admin-surface-row" key=${p.id}>
                        <span style="font-size:18px;margin-right:6px;">${p.icon || '\ud83e\udd16'}</span>
                        <div style="flex:1;min-width:0;">
                            <strong>${p.name}</strong>
                            <span class="text-muted" style="margin-left:6px;font-size:11px;">@${p.handle || '?'}</span>
                            ${p.scope && html`<span class="badge" style="margin-left:6px;">${p.scope}</span>`}
                        </div>
                        <div class="admin-actions-cell">
                            <button class="btn-small" onClick=${() => startEdit(p)}>Edit</button>
                            <button class="btn-small btn-danger" onClick=${() => deletePersona(p.id)}>Delete</button>
                        </div>
                    </div>
                `)}
            </div>
        </div>
    `;
}
