/* Instellingen screen */

function SchermInstellingen() {
  const [providers, setProviders] = useState({});
  const [form, setForm] = useState({ provider: 'anthropic', api_key: '', base_url: 'http://localhost:11434', region: 'eu-central-1' });
  const [status, setStatus] = useState(null);
  const [testen, setTesten] = useState(false);
  const [logboek, setLogboek] = useState([]);
  const [logLaden, setLogLaden] = useState(false);
  const isOllama = form.provider === 'ollama';
  const isBedrock = form.provider === 'bedrock';

  // Standaard provider + model voor de pipeline-startform
  const [std, setStd] = useState({ provider: 'anthropic', model: '' });
  const [stdOllamaModellen, setStdOllamaModellen] = useState([]);
  const [stdStatus, setStdStatus] = useState(null);
  const [stdBezig, setStdBezig] = useState(false);

  const [providerModellen, setProviderModellen] = useState({});
  const [modelForm, setModelForm] = useState({ provider: 'anthropic', nieuw: '' });
  const [modelStatus, setModelStatus] = useState(null);

  async function laadModellen() {
    try {
      const d = await fetch(`${API}/config/providers/models`).then(r => r.ok ? r.json() : {});
      setProviderModellen(d);
    } catch (e) {}
  }
  useEffect(() => { laadModellen(); }, []);

  async function laadStandaard() {
    const d = await fetch(`${API}/config/standaard`).then(r => r.ok ? r.json() : {}).catch(() => ({}));
    if (d && d.provider) setStd({ provider: d.provider, model: d.model || '' });
  }
  useEffect(() => { laadStandaard(); }, []);

  useEffect(() => {
    if (std.provider !== 'ollama') { setStdOllamaModellen([]); return; }
    fetch(`${API}/config/providers/ollama/models`)
      .then(r => r.ok ? r.json() : { models: [] })
      .then(d => setStdOllamaModellen(d.models || []))
      .catch(() => setStdOllamaModellen([]));
  }, [std.provider]);

  const stdModelOpties = std.provider === 'ollama'
    ? stdOllamaModellen
    : (providerModellen[std.provider] || []);

  async function slaStandaardOp() {
    setStdStatus(null); setStdBezig(true);
    try {
      const r = await fetch(`${API}/config/standaard`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ provider: std.provider, model: std.model || null }),
      });
      setStdStatus(r.ok ? { kind: 'success', msg: 'Standaard opgeslagen.' } : { kind: 'error', msg: 'Opslaan mislukt.' });
    } catch (e) {
      setStdStatus({ kind: 'error', msg: `Opslaan mislukt: ${e.message}` });
    } finally { setStdBezig(false); }
  }

  async function laadLogboek() {
    setLogLaden(true);
    try {
      const d = await fetch(`${API}/auth-log?limit=100`).then(r => r.ok ? r.json() : []).catch(() => []);
      setLogboek(Array.isArray(d) ? d : []);
    } finally { setLogLaden(false); }
  }
  useEffect(() => { laadLogboek(); }, []);

  const LOG_KIND = { login_ok: 'success', login_fout: 'error', lockout: 'warning', logout: 'neutral' };
  const LOG_LABEL = { login_ok: 'Ingelogd', login_fout: 'Mislukt', lockout: 'Geblokkeerd', logout: 'Uitgelogd' };

  async function laad() {
    const p = await fetch(`${API}/config/providers`).then(r => r.json()).catch(() => ({}));
    setProviders(p);
    const details = await fetch(`${API}/config/providers/public`).then(r => r.json()).catch(() => ({}));
    setForm(f => ({
      ...f,
      base_url: details.ollama?.base_url || f.base_url,
      region: details.bedrock?.region || f.region,
    }));
  }
  useEffect(() => { laad(); }, []);

  async function opslaan() {
    setStatus(null);
    const r = await fetch(`${API}/config/providers`, {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify(form)
    });
    if (r.ok) { setStatus({ kind: 'success', msg: 'Opgeslagen.' }); setForm(f => ({...f, api_key: ''})); laad(); }
    else { setStatus({ kind: 'error', msg: 'Opslaan mislukt.' }); }
  }

  async function testProvider() {
    setStatus(null);
    setTesten(true);
    try {
      const params = new URLSearchParams();
      if (isOllama && form.base_url) params.append('base_url', form.base_url);
      if (!isOllama && form.api_key) params.append('api_key', form.api_key);
      const qs = params.toString() ? `?${params.toString()}` : '';
      const data = await fetch(`${API}/config/providers/test/${form.provider}${qs}`).then(r => r.json());
      if (data.ok) {
        const extra = isOllama && data.models?.length ? ` Modellen: ${data.models.join(', ')}` : '';
        setStatus({ kind: 'success', msg: `Verbinding werkt.${extra}` });
      } else {
        setStatus({ kind: 'error', msg: `Test mislukt: ${data.fout || 'onbekende fout'}` });
      }
    } catch(e) {
      setStatus({ kind: 'error', msg: `Test mislukt: ${e.message}` });
    } finally {
      setTesten(false);
    }
  }

  async function voegModelToe() {
    const naam = modelForm.nieuw.trim();
    if (!naam) return;
    const huidig = providerModellen[modelForm.provider] || [];
    if (huidig.includes(naam)) {
      setModelStatus({ kind: 'error', msg: `"${naam}" staat al in de lijst.` });
      return;
    }
    const nieuw = [...huidig, naam];
    setModelStatus(null);
    try {
      const r = await fetch(`${API}/config/providers/models`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ provider: modelForm.provider, models: nieuw }),
      });
      if (r.ok) {
        setProviderModellen(p => ({ ...p, [modelForm.provider]: nieuw }));
        setModelForm(f => ({ ...f, nieuw: '' }));
        setModelStatus({ kind: 'success', msg: `"${naam}" toegevoegd.` });
        laadModellen();
      } else {
        setModelStatus({ kind: 'error', msg: 'Toevoegen mislukt.' });
      }
    } catch (e) {
      setModelStatus({ kind: 'error', msg: `Toevoegen mislukt: ${e.message}` });
    }
  }

  async function verwijderModel(model) {
    const huidig = providerModellen[modelForm.provider] || [];
    const nieuw = huidig.filter(m => m !== model);
    setModelStatus(null);
    try {
      const r = await fetch(`${API}/config/providers/models`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ provider: modelForm.provider, models: nieuw }),
      });
      if (r.ok) {
        setProviderModellen(p => ({ ...p, [modelForm.provider]: nieuw }));
        setModelStatus({ kind: 'success', msg: `"${model}" verwijderd.` });
        laadModellen();
      } else {
        setModelStatus({ kind: 'error', msg: 'Verwijderen mislukt.' });
      }
    } catch (e) {
      setModelStatus({ kind: 'error', msg: `Verwijderen mislukt: ${e.message}` });
    }
  }

  return (
    <div className="bd-page">
      <div className="bd-page-head">
        <div><h1>Instellingen</h1><p>Configureer AI-providers en systeemopties.</p></div>
      </div>

      <div className="bd-card">
        <div className="bd-card-head"><h2><Icon name="key-round" /> AI Providers</h2></div>
        {status && <Alert kind={status.kind}>{status.msg}</Alert>}
        <div className="bd-grid-2">
          <Field label="Provider">
            <select className="bd-select" value={form.provider} onChange={e => setForm(f => ({
              ...f,
              provider: e.target.value,
              base_url: e.target.value === 'ollama' && !f.base_url ? 'http://localhost:11434' : f.base_url,
            }))}>
              <option value="anthropic">Anthropic</option>
              <option value="openai">OpenAI</option>
              <option value="google">Google</option>
              <option value="ollama">Ollama (lokaal)</option>
              <option value="bedrock">AWS Bedrock</option>
              <option value="nebul">Nebul AI Studio</option>
            </select>
          </Field>
          {isOllama && (
            <Field label="Ollama URL" hint="Gebruik normaal http://localhost:11434. De app voegt /api zelf toe.">
              <input type="url" className="bd-input" placeholder="http://localhost:11434" value={form.base_url}
                     onChange={e => setForm(f => ({...f, base_url: e.target.value}))} />
            </Field>
          )}
          {isBedrock && (
            <Field label="AWS region" hint="Bedrock gebruikt AWS credentials (env vars / IAM). Geen API-sleutel nodig.">
              <input type="text" className="bd-input" placeholder="eu-central-1" value={form.region}
                     onChange={e => setForm(f => ({...f, region: e.target.value}))} />
            </Field>
          )}
          {!isOllama && !isBedrock && (
            <Field label="API Key">
              <input type="password" className="bd-input" placeholder="sk-…" value={form.api_key}
                     onChange={e => setForm(f => ({...f, api_key: e.target.value}))} />
            </Field>
          )}
        </div>
        <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
          <Btn kind="primary" icon="save" onClick={opslaan} disabled={isOllama ? !form.base_url : isBedrock ? !form.region : !form.api_key}>Opslaan</Btn>
          <Btn kind="secondary" icon="plug-zap" onClick={testProvider} disabled={testen || (isOllama ? !form.base_url : isBedrock ? !form.region : false)}>
            {testen ? 'Testen...' : 'Test verbinding'}
          </Btn>
        </div>

        <div style={{marginTop:20, borderTop:'1px solid var(--color-border-light)', paddingTop:16}}>
          <div style={{fontSize:'var(--font-size-xs)', textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-muted)', fontWeight:600, marginBottom:10}}>Geconfigureerde providers</div>
          {Object.entries(providers).map(([k,v]) => (
            <div key={k} style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'8px 0', borderBottom:'1px solid var(--color-border-light)'}}>
              <span style={{fontSize:'var(--font-size-sm)', fontWeight:500, textTransform:'capitalize'}}>{k}</span>
              {v ? <Badge kind="success">Geconfigureerd</Badge> : <Badge kind="neutral">Niet ingesteld</Badge>}
            </div>
          ))}
        </div>
      </div>

      <div className="bd-card">
        <div className="bd-card-head"><h2><Icon name="sliders-horizontal" /> Standaard voor pipeline</h2></div>
        <p style={{ color: 'var(--text-muted)', fontSize: 'var(--font-size-sm)', marginTop: -4, marginBottom: 'var(--space-3)' }}>
          Provider en model die de pipeline-startform standaard voorinvult.
        </p>
        {stdStatus && <Alert kind={stdStatus.kind}>{stdStatus.msg}</Alert>}
        <div className="bd-grid-2">
          <Field label="Standaard provider">
            <select className="bd-select" value={std.provider}
              onChange={e => {
                const provider = e.target.value;
                const opties = provider === 'ollama' ? stdOllamaModellen : (providerModellen[provider] || []);
                setStd({ provider, model: opties[0] || '' });
              }}>
              {Object.entries(providers).map(([k, v]) => (
                <option key={k} value={k}>{k}{v ? '' : ' (niet geconfigureerd)'}</option>
              ))}
            </select>
          </Field>
          <Field label="Standaard model" hint="Kies een suggestie of typ zelf een exacte modelnaam.">
            <input className="bd-input" list="std-model-opties" placeholder="bijv. qwen2.5vl:7b"
              value={std.model} onChange={e => setStd(s => ({ ...s, model: e.target.value }))} />
            <datalist id="std-model-opties">
              {stdModelOpties.map(m => <option key={m} value={m} />)}
            </datalist>
          </Field>
        </div>
        <Btn kind="primary" icon="save" onClick={slaStandaardOp} disabled={stdBezig || !std.provider}>
          {stdBezig ? 'Opslaan…' : 'Opslaan als standaard'}
        </Btn>
      </div>

      <div className="bd-card">
        <div className="bd-card-head"><h2><Icon name="list" /> Modellen per provider</h2></div>
        <p style={{ color: 'var(--text-muted)', fontSize: 'var(--font-size-sm)', marginTop: -4, marginBottom: 'var(--space-3)' }}>
          Voeg modellen toe of verwijder ze per provider. Ollama-modellen worden automatisch opgehaald.
        </p>
        {modelStatus && <Alert kind={modelStatus.kind}>{modelStatus.msg}</Alert>}
        <div className="bd-grid-2">
          <Field label="Provider">
            <select className="bd-select" value={modelForm.provider}
              onChange={e => setModelForm(f => ({ ...f, provider: e.target.value, nieuw: '' }))}>
              {['anthropic', 'openai', 'google', 'bedrock', 'nebul'].map(k => (
                <option key={k} value={k}>{k}</option>
              ))}
            </select>
          </Field>
          <Field label="Model toevoegen" hint="Typ een exacte modelnaam en klik op Toevoegen.">
            <div style={{display:'flex', gap:8}}>
              <input className="bd-input" style={{flex:1}} placeholder="bijv. claude-sonnet-4-6"
                value={modelForm.nieuw} onChange={e => setModelForm(f => ({ ...f, nieuw: e.target.value }))}
                onKeyDown={e => { if (e.key === 'Enter' && modelForm.nieuw.trim()) voegModelToe(); }} />
              <Btn kind="secondary" icon="plus" onClick={voegModelToe} disabled={!modelForm.nieuw.trim()}>Toevoegen</Btn>
            </div>
          </Field>
        </div>
        {providerModellen[modelForm.provider] && providerModellen[modelForm.provider].length > 0 && (
          <div style={{marginTop:12}}>
            <div style={{fontSize:'var(--font-size-xs)', textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-muted)', fontWeight:600, marginBottom:8}}>
              Modellen voor {modelForm.provider}
            </div>
            <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
              {providerModellen[modelForm.provider].map((m, i) => (
                <span key={i} style={{
                  display:'inline-flex', alignItems:'center', gap:4,
                  padding:'4px 10px', borderRadius:4, fontSize:'var(--font-size-sm)',
                  background:'var(--color-surface-hover)', border:'1px solid var(--color-border-light)',
                }}>
                  <span className="bd-mono" style={{fontSize:'var(--font-size-xs)'}}>{m}</span>
                  <button type="button" style={{background:'none',border:'none',cursor:'pointer',color:'var(--color-status-error)',padding:0,lineHeight:1}}
                    title="Verwijderen" onClick={() => verwijderModel(m)}>×</button>
                </span>
              ))}
            </div>
          </div>
        )}
        {(!providerModellen[modelForm.provider] || providerModellen[modelForm.provider].length === 0) && (
          <div style={{color:'var(--text-muted)', fontSize:'var(--font-size-sm)', marginTop:8}}>
            Geen modellen geconfigureerd voor {modelForm.provider}.
          </div>
        )}
      </div>

      <div className="bd-card">
        <div className="bd-card-head" style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <h2><Icon name="shield" /> Inlogpogingen</h2>
          <Btn kind="secondary" icon="refresh-cw" onClick={laadLogboek} disabled={logLaden}>
            {logLaden ? 'Laden…' : 'Vernieuwen'}
          </Btn>
        </div>
        {logboek.length === 0 ? (
          <div style={{padding:'var(--space-5) 0', textAlign:'center', color:'var(--text-muted)', fontSize:'var(--font-size-sm)'}}>
            Nog geen inloggebeurtenissen vastgelegd.
          </div>
        ) : (
          <div style={{overflowX:'auto'}}>
            <table className="bd-table">
              <thead><tr><th>Tijd</th><th>Gebeurtenis</th><th>Gebruiker</th><th>IP</th><th>Detail</th></tr></thead>
              <tbody>
                {logboek.map((r, i) => (
                  <tr key={i}>
                    <td className="bd-mono" style={{whiteSpace:'nowrap'}}>{(r.tijd || '').replace('T',' ').slice(0,19)}</td>
                    <td><Badge kind={LOG_KIND[r.gebeurtenis] || 'neutral'}>{LOG_LABEL[r.gebeurtenis] || r.gebeurtenis}</Badge></td>
                    <td>{r.gebruikersnaam || '—'}</td>
                    <td className="bd-mono">{r.ip || '—'}</td>
                    <td style={{fontSize:'var(--font-size-xs)', color:'var(--text-muted)', maxWidth:320}}>{r.detail || (r.user_agent ? r.user_agent.slice(0,60) : '')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

window.SchermInstellingen = SchermInstellingen;
