// Super Admin panel — configure the AI provider that powers
// /api/ai/generate-questions (and future AI features).
const { useState: useState_sa, useEffect: useEffect_sa } = React;

function SuperAdminView() {
  const [providers, setProviders] = useState_sa([]);
  const [loading, setLoading] = useState_sa(true);
  const [providerId, setProviderId] = useState_sa('stub');
  const [model, setModel] = useState_sa('stub');
  const [apiKey, setApiKey] = useState_sa('');
  const [keepKey, setKeepKey] = useState_sa(false); // true when an existing key is preserved
  const [baseURL, setBaseURL] = useState_sa('');
  const [temperature, setTemperature] = useState_sa(0.4);
  const [savedAt, setSavedAt] = useState_sa(null);
  const [error, setError] = useState_sa(null);
  const [testing, setTesting] = useState_sa(false);
  const [testResult, setTestResult] = useState_sa(null);

  // Load providers + current settings in parallel
  useEffect_sa(() => {
    Promise.all([window.api.listAiProviders(), window.api.getAiSettings()])
      .then(([p, s]) => {
        setProviders(p.providers || []);
        if (s.settings) {
          setProviderId(s.settings.provider);
          setModel(s.settings.model);
          setBaseURL(s.settings.baseURL || '');
          setTemperature(s.settings.temperature ?? 0.4);
          if (s.settings.hasApiKey) {
            setApiKey(s.settings.apiKeyMask || '••••');
            setKeepKey(true);
          }
        }
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  const provider = providers.find((p) => p.id === providerId);
  // When user picks a new provider, default to its first model and clear stored key flag
  const onProviderChange = (id) => {
    setProviderId(id);
    const p = providers.find((x) => x.id === id);
    if (p) {
      setModel(p.models[0]?.id || '');
      setBaseURL('');
    }
    setKeepKey(false);
    setApiKey('');
    setTestResult(null);
  };

  const save = async () => {
    setError(null);
    setSavedAt(null);
    try {
      const body = {
        provider: providerId,
        model,
        baseURL: baseURL || null,
        temperature,
      };
      // Only send apiKey if user typed a fresh one (not the masked placeholder)
      if (apiKey && !keepKey) body.apiKey = apiKey;
      await window.api.saveAiSettings(body);
      setSavedAt(new Date());
      setKeepKey(true); // any newly entered key is now stored
    } catch (err) {
      setError(err.message);
    }
  };

  const test = async () => {
    setTesting(true);
    setTestResult(null);
    try {
      const body = {};
      // If user typed a new key, test with it (don't save first)
      if (apiKey && !keepKey) {
        body.provider = providerId;
        body.model = model;
        body.apiKey = apiKey;
        if (baseURL) body.baseURL = baseURL;
      }
      const r = await window.api.testAi(body);
      setTestResult(r);
    } catch (err) {
      setTestResult({ ok: false, error: err.message });
    } finally {
      setTesting(false);
    }
  };

  if (loading) {
    return (
      <div style={{ display: 'grid', placeItems: 'center', height: '100%', color: 'var(--ink-3)' }}>
        Memuat pengaturan…
      </div>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <TopBar
        title="Super Admin · Konfigurasi AI"
        subtitle="Pilih provider & model AI yang dipakai untuk generate pertanyaan, insight, dll."
      />
      <div className="scroll" style={{ flex: 1, overflow: 'auto', padding: 24, background: 'var(--bg)' }}>
        <div style={{ maxWidth: 880, margin: '0 auto' }}>

          <div className="card" style={{ padding: 22, marginBottom: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <I.Sparkle size={16} style={{ color: 'var(--primary)' }} />
              <h2 style={{ margin: 0, fontSize: 17, fontWeight: 600, letterSpacing: '-0.01em' }}>
                AI Provider
              </h2>
            </div>
            <p style={{ margin: '0 0 16px', fontSize: 13, color: 'var(--ink-3)' }}>
              Konfigurasi global — berlaku untuk semua tenant. API key disimpan
              terenkripsi di server dan tidak pernah dikirim balik ke browser.
            </p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <label className="label">Provider</label>
                <select
                  className="select"
                  value={providerId}
                  onChange={(e) => onProviderChange(e.target.value)}
                >
                  {providers.map((p) => (
                    <option key={p.id} value={p.id}>{p.label}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="label">Model</label>
                <select
                  className="select"
                  value={model}
                  onChange={(e) => { setModel(e.target.value); setTestResult(null); }}
                >
                  {(provider?.models || []).map((m) => (
                    <option key={m.id} value={m.id}>{m.label}</option>
                  ))}
                </select>
                {provider?.models.find((m) => m.id === model)?.hint && (
                  <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>
                    {provider.models.find((m) => m.id === model).hint}
                  </div>
                )}
              </div>

              <div style={{ gridColumn: '1 / -1' }}>
                <label className="label">API Key</label>
                <div style={{ position: 'relative' }}>
                  <input
                    className="input mono"
                    type={keepKey ? 'text' : 'password'}
                    value={apiKey}
                    onChange={(e) => { setApiKey(e.target.value); setKeepKey(false); setTestResult(null); }}
                    placeholder={
                      providerId === 'stub'
                        ? 'Tidak diperlukan — provider stub'
                        : 'Tempel API key dari dashboard provider'
                    }
                    disabled={providerId === 'stub'}
                    style={{ fontFamily: 'var(--font-mono)', fontSize: 13 }}
                  />
                  {keepKey && (
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>
                      Tersimpan. Edit di sini untuk mengganti, atau biarkan untuk pakai yang sudah ada.
                    </div>
                  )}
                </div>
              </div>

              <div>
                <label className="label">
                  Base URL <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>(opsional)</span>
                </label>
                <input
                  className="input mono"
                  value={baseURL}
                  onChange={(e) => setBaseURL(e.target.value)}
                  placeholder={provider?.defaultBaseURL || ''}
                  style={{ fontSize: 12.5 }}
                />
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>
                  Override untuk proxy / regional endpoint.
                </div>
              </div>

              <div>
                <label className="label">Temperature ({temperature.toFixed(2)})</label>
                <input
                  type="range"
                  min="0" max="1" step="0.05"
                  value={temperature}
                  onChange={(e) => setTemperature(Number(e.target.value))}
                  style={{ width: '100%' }}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
                  <span>Konsisten</span><span>Kreatif</span>
                </div>
              </div>
            </div>
          </div>

          {/* Provider info card */}
          {provider && (
            <div className="card" style={{ padding: 16, marginBottom: 14, background: 'var(--bg-2)' }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
                {provider.label}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>
                {provider.defaultBaseURL || '— no remote endpoint —'}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10 }}>
                {provider.models.map((m) => (
                  <span key={m.id} className={`badge ${m.id === model ? 'badge-primary' : ''}`} style={{ fontSize: 11 }}>
                    {m.label}
                  </span>
                ))}
              </div>
            </div>
          )}

          {error && (
            <div style={{ padding: 12, borderRadius: 10, background: 'var(--danger-soft)', color: 'var(--danger)', fontSize: 13, marginBottom: 12 }}>
              {error}
            </div>
          )}

          {testResult && (
            <div style={{
              padding: 12, borderRadius: 10, marginBottom: 12,
              background: testResult.ok ? 'var(--success-soft)' : 'var(--danger-soft)',
              color: testResult.ok ? 'oklch(0.32 0.10 155)' : 'var(--danger)',
              fontSize: 13,
            }}>
              <div style={{ fontWeight: 600 }}>
                {testResult.ok ? '✓ Tes berhasil' : '✗ Tes gagal'}
                {testResult.provider && ` · ${testResult.provider}/${testResult.model || ''}`}
              </div>
              {testResult.sample && (
                <div style={{ marginTop: 6, fontSize: 12.5, fontFamily: 'var(--font-mono)' }}>
                  "{testResult.sample}"
                </div>
              )}
              {testResult.error && (
                <div style={{ marginTop: 6, fontSize: 12, fontFamily: 'var(--font-mono)' }}>
                  {testResult.error}
                </div>
              )}
            </div>
          )}

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button
              className="btn btn-ghost"
              onClick={test}
              disabled={testing || (providerId !== 'stub' && !apiKey)}
            >
              <I.Lightning size={14} />{testing ? 'Menguji…' : 'Tes Koneksi'}
            </button>
            <button className="btn btn-primary" onClick={save}>
              <I.Check size={14} />Simpan Pengaturan
            </button>
            {savedAt && (
              <span style={{ fontSize: 12, color: 'oklch(0.42 0.12 155)' }}>
                Tersimpan {savedAt.toLocaleTimeString('id-ID')}
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.SuperAdminView = SuperAdminView;
