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

export default function SettingsSection() {
    const [cfg, setCfg] = useState({});
    const [models, setModels] = useState([]);
    const [vault, setVault] = useState(null);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const load = useCallback(async () => {
        try {
            const [s, m, v] = await Promise.all([
                sw.api.admin.settings.get(),
                sw.api.admin.models.list().catch(() => []),
                sw.api.admin.vault.status().catch(() => null),
            ]);
            const raw = s || {};
            const pol = raw.policies || {};
            const cfg_ = raw.settings || {};
            setCfg({
                allow_registration: pol.allow_registration === 'true',
                registration_default_state: cfg_.registration_default_state || 'pending',
                system_prompt: cfg_.system_prompt || '',
                default_model: pol.default_model || '',
                allow_user_byok: pol.allow_user_byok === 'true',
                allow_user_personas: pol.allow_user_personas === 'true',
                allow_kb_direct_access: pol.allow_kb_direct_access === 'true' || pol.kb_direct_access === 'true',
                banner_enabled: !!cfg_.banner?.enabled,
                banner_text: cfg_.banner?.text || '',
                banner_bg: cfg_.banner?.bg || '#007a33',
                banner_fg: cfg_.banner?.fg || '#ffffff',
                banner_position: cfg_.banner?.position || 'both',
                message_enabled: !!cfg_.message?.enabled,
                message_text: cfg_.message?.text || '',
                message_variant: cfg_.message?.variant || 'info',
                footer_enabled: !!cfg_.footer?.enabled,
                footer_text: cfg_.footer?.text || '',
                search_provider: cfg_.search_provider || 'duckduckgo',
                search_endpoint: cfg_.search_endpoint || '',
                search_api_key: cfg_.search_api_key || '',
                search_max_results: cfg_.search_max_results || 5,
                compaction_enabled: !!cfg_.auto_compaction_enabled,
                compaction_threshold: cfg_.compaction_threshold || 70,
                compaction_cooldown: cfg_.compaction_cooldown || 30,
                memory_extraction_enabled: !!cfg_.memory_extraction_enabled,
                memory_auto_approve: !!cfg_.memory_auto_approve,
            });
            setModels(m || []);
            setVault(v);
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, []);

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

    function set(key, val) { setCfg(prev => ({ ...prev, [key]: val })); }

    async function save() {
        setSaving(true);
        try {
            // Policies
            await sw.api.admin.settings.update('allow_registration', { value: String(cfg.allow_registration) });
            await sw.api.admin.settings.update('registration_default_state', { value: cfg.registration_default_state });
            await sw.api.admin.settings.update('allow_user_byok', { value: String(cfg.allow_user_byok) });
            await sw.api.admin.settings.update('allow_user_personas', { value: String(cfg.allow_user_personas) });
            await sw.api.admin.settings.update('allow_kb_direct_access', { value: String(cfg.allow_kb_direct_access) });

            // System prompt & default model
            await sw.api.admin.settings.update('system_prompt', { value: cfg.system_prompt });
            if (cfg.default_model) await sw.api.admin.settings.update('default_model', { value: cfg.default_model });

            // Banner
            await sw.api.admin.settings.update('banner', { value: {
                enabled: cfg.banner_enabled,
                text: cfg.banner_text,
                bg: cfg.banner_bg,
                fg: cfg.banner_fg,
                position: cfg.banner_position,
            }});

            // Message bar
            await sw.api.admin.settings.update('message', { value: {
                enabled: cfg.message_enabled,
                text: cfg.message_text,
                variant: cfg.message_variant,
            }});

            // Footer
            await sw.api.admin.settings.update('footer', { value: {
                enabled: cfg.footer_enabled,
                text: cfg.footer_text,
            }});

            // Search
            await sw.api.admin.settings.update('search_provider', { value: cfg.search_provider });
            if (cfg.search_provider === 'searxng') {
                await sw.api.admin.settings.update('search_endpoint', { value: cfg.search_endpoint });
                await sw.api.admin.settings.update('search_api_key', { value: cfg.search_api_key });
            }
            await sw.api.admin.settings.update('search_max_results', { value: cfg.search_max_results });

            // Compaction
            await sw.api.admin.settings.update('auto_compaction_enabled', { value: String(cfg.compaction_enabled) });
            await sw.api.admin.settings.update('compaction_threshold', { value: cfg.compaction_threshold });
            await sw.api.admin.settings.update('compaction_cooldown', { value: cfg.compaction_cooldown });

            // Memory
            await sw.api.admin.settings.update('memory_extraction_enabled', { value: String(cfg.memory_extraction_enabled) });
            await sw.api.admin.settings.update('memory_auto_approve', { value: String(cfg.memory_auto_approve) });

            sw.toast('Settings saved', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSaving(false); }
    }

    async function testEmail() {
        try {
            await sw.api.admin.notifications.testEmail();
            sw.toast('Test email sent', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
    }

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

    return html`
        <div class="admin-settings-form">
            <div class="settings-section"><h3>Registration</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.allow_registration} onChange=${e => set('allow_registration', e.target.checked)} /><span class="toggle-track"></span><span>Allow new user registration</span></label>
                <div class="form-group" style="margin-top:8px;"><label>Default state</label>
                    <select value=${cfg.registration_default_state} onChange=${e => set('registration_default_state', e.target.value)}>
                        <option value="pending">Pending (require approval)</option>
                        <option value="active">Active (auto-approve)</option>
                    </select>
                </div>
            </div>

            <div class="settings-section"><h3>System Prompt</h3>
                <textarea rows="4" placeholder="Global system prompt\u2026" value=${cfg.system_prompt} onInput=${e => set('system_prompt', e.target.value)}></textarea>
            </div>

            <div class="settings-section"><h3>Default Model</h3>
                <select value=${cfg.default_model} onChange=${e => set('default_model', e.target.value)}>
                    <option value="">-- None (first visible) --</option>
                    ${models.map(m => html`<option key=${m.id} value=${m.model_id || m.id}>${m.display_name || m.model_id || m.id}</option>`)}
                </select>
            </div>

            <div class="settings-section"><h3>Policies</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.allow_user_byok} onChange=${e => set('allow_user_byok', e.target.checked)} /><span class="toggle-track"></span><span>Allow BYOK (user API keys)</span></label>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.allow_user_personas} onChange=${e => set('allow_user_personas', e.target.checked)} /><span class="toggle-track"></span><span>Allow user personas</span></label>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.allow_kb_direct_access} onChange=${e => set('allow_kb_direct_access', e.target.checked)} /><span class="toggle-track"></span><span>Allow direct KB access</span></label>
            </div>

            <div class="settings-section"><h3>Environment Banner</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.banner_enabled} onChange=${e => set('banner_enabled', e.target.checked)} /><span class="toggle-track"></span><span>Show environment banner</span></label>
                ${cfg.banner_enabled && html`
                    <div style="margin-top:8px;">
                        <div class="form-group"><label>Text</label><input value=${cfg.banner_text} onInput=${e => set('banner_text', e.target.value)} placeholder="DEVELOPMENT" /></div>
                        <div class="form-row">
                            <div class="form-group"><label>Background</label><input type="color" value=${cfg.banner_bg} onInput=${e => set('banner_bg', e.target.value)} /></div>
                            <div class="form-group"><label>Foreground</label><input type="color" value=${cfg.banner_fg} onInput=${e => set('banner_fg', e.target.value)} /></div>
                            <div class="form-group"><label>Position</label>
                                <select value=${cfg.banner_position} onChange=${e => set('banner_position', e.target.value)}>
                                    <option value="both">Both</option><option value="top">Top</option><option value="bottom">Bottom</option>
                                </select>
                            </div>
                        </div>
                        <div class="banner-preview" style="margin-top:8px;padding:4px 12px;text-align:center;font-size:12px;font-weight:600;border-radius:4px;background:${cfg.banner_bg};color:${cfg.banner_fg};">${cfg.banner_text || 'PREVIEW'}</div>
                    </div>
                `}
            </div>

            <div class="settings-section"><h3>Message Bar</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.message_enabled} onChange=${e => set('message_enabled', e.target.checked)} /><span class="toggle-track"></span><span>Show dismissible message bar</span></label>
                ${cfg.message_enabled && html`
                    <div style="margin-top:8px;">
                        <div class="form-group"><label>Text</label><input value=${cfg.message_text} onInput=${e => set('message_text', e.target.value)} placeholder="System maintenance scheduled..." /></div>
                        <div class="form-group"><label>Variant</label>
                            <select value=${cfg.message_variant} onChange=${e => set('message_variant', e.target.value)}>
                                <option value="info">Info</option>
                                <option value="warn">Warning</option>
                                <option value="error">Error</option>
                                <option value="success">Success</option>
                            </select>
                        </div>
                    </div>
                `}
            </div>

            <div class="settings-section"><h3>Footer</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.footer_enabled} onChange=${e => set('footer_enabled', e.target.checked)} /><span class="toggle-track"></span><span>Show footer bar</span></label>
                ${cfg.footer_enabled && html`
                    <div style="margin-top:8px;">
                        <div class="form-group"><label>Text</label><input value=${cfg.footer_text} onInput=${e => set('footer_text', e.target.value)} placeholder="Powered by Chat Switchboard" /></div>
                    </div>
                `}
            </div>

            <div class="settings-section"><h3>Web Search</h3>
                <div class="form-group"><label>Provider</label>
                    <select value=${cfg.search_provider} onChange=${e => set('search_provider', e.target.value)}>
                        <option value="duckduckgo">DuckDuckGo</option><option value="searxng">SearXNG</option>
                    </select>
                </div>
                ${cfg.search_provider === 'searxng' && html`
                    <div class="form-group"><label>Endpoint</label><input value=${cfg.search_endpoint} onInput=${e => set('search_endpoint', e.target.value)} placeholder="https://searxng.example.com" /></div>
                    <div class="form-group"><label>API Key</label><input value=${cfg.search_api_key} onInput=${e => set('search_api_key', e.target.value)} placeholder="Optional" /></div>
                `}
                <div class="form-group"><label>Max Results</label><input type="number" min="1" max="20" value=${cfg.search_max_results} onInput=${e => set('search_max_results', parseInt(e.target.value) || 5)} /></div>
            </div>

            <div class="settings-section"><h3>Auto-Compaction</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.compaction_enabled} onChange=${e => set('compaction_enabled', e.target.checked)} /><span class="toggle-track"></span><span>Enable auto-compaction</span></label>
                ${cfg.compaction_enabled && html`
                    <div class="form-row" style="margin-top:8px;">
                        <div class="form-group"><label>Threshold (%)</label><input type="number" min="50" max="95" value=${cfg.compaction_threshold} onInput=${e => set('compaction_threshold', parseInt(e.target.value))} /></div>
                        <div class="form-group"><label>Cooldown (min)</label><input type="number" min="5" max="1440" value=${cfg.compaction_cooldown} onInput=${e => set('compaction_cooldown', parseInt(e.target.value))} /></div>
                    </div>
                `}
            </div>

            <div class="settings-section"><h3>Memory Extraction</h3>
                <label class="toggle-label"><input type="checkbox" checked=${cfg.memory_extraction_enabled} onChange=${e => set('memory_extraction_enabled', e.target.checked)} /><span class="toggle-track"></span><span>Enable memory extraction</span></label>
                ${cfg.memory_extraction_enabled && html`
                    <label class="toggle-label" style="margin-top:8px;"><input type="checkbox" checked=${cfg.memory_auto_approve} onChange=${e => set('memory_auto_approve', e.target.checked)} /><span class="toggle-track"></span><span>Auto-approve extracted memories</span></label>
                `}
            </div>

            <div class="settings-section"><h3>Encryption Vault</h3>
                ${vault
                    ? html`<div class="text-muted" style="font-size:12px;">Key set: ${vault.encryption_key_set ? 'Yes' : 'No'} \u2022 User vaults: ${vault.user_vaults_count ?? '?'}</div>`
                    : html`<span class="text-muted" style="font-size:12px;">Could not load vault status</span>`
                }
            </div>

            <div class="settings-section"><h3>Email</h3>
                <button class="btn-small" onClick=${testEmail}>Send Test Email</button>
            </div>

            <div style="display:flex;gap:8px;align-items:center;margin-top:16px;">
                <button class="btn-md btn-primary" onClick=${save} disabled=${saving}>${saving ? 'Saving\u2026' : 'Save Settings'}</button>
            </div>
        </div>
    `;
}
