// Tela "Buscar na base" — busca de proveniência em linguagem natural.
// O admin pergunta ONDE um conteúdo/instrução está cadastrado; a IA interna
// (endpoint /api/admin/kb-search) responde onde está + lista fontes clicáveis
// que abrem o editor certo. NÃO responde o conteúdo em si — só localiza.
function ScreenKbSearch() {
  const toast = useToast();
  // Persiste a última busca em window.__kbSearchState pra sobreviver a uma
  // eventual navegação (ex.: fonte sem modal próprio) e ser restaurada no mount.
  const saved = window.__kbSearchState || {};
  const [q, setQ] = useState(saved.q || '');
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(saved.result || null); // { resposta, fontes }
  const [opening, setOpening] = useState(null); // ref da fonte que está carregando
  const [viewing, setViewing] = useState(null); // documento → FileViewModal
  const [editingCtx, setEditingCtx] = useState(null); // contexto/diretriz → ContextEditModal

  // Sempre que a busca muda, guarda o estado pra restaurar ao voltar pra tela.
  useEffect(() => { window.__kbSearchState = { q, result }; }, [q, result]);

  const run = () => {
    const query = q.trim();
    if (query.length < 3) { toast({ title: 'Digite ao menos 3 caracteres', kind: 'info' }); return; }
    setBusy(true);
    setResult(null);
    api('/api/admin/kb-search', { method: 'POST', body: { query } })
      .then((r) => setResult(r))
      .catch((e) => toast({ title: 'Falha na busca', msg: e.message, kind: 'error' }))
      .finally(() => setBusy(false));
  };

  // Clica numa fonte → abre o editor NO PRÓPRIO modal desta página, sem navegar
  // (assim a pesquisa continua ativa ao fechar). Só cai pra navegação quando a
  // fonte não tem modal reaproveitável aqui (ex.: system prompt = tela inteira).
  const openSource = (f) => {
    const ref = f.ref || `${f.kind}:${f.id}`;

    if (f.kind === 'documento' && window.FileViewModal) {
      setOpening(ref);
      api('/api/admin/files/' + f.id)
        .then((data) => {
          const ft = String(data.file_type || '').toLowerCase();
          const type = ft.includes('pdf') ? 'PDF'
                     : ft.includes('docx') || ft.includes('word') ? 'DOCX'
                     : ft.includes('image') || ft.includes('jpg') || ft.includes('png') ? 'IMG'
                     : ft === 'md' || ft === 'markdown' ? 'MD'
                     : ft === 'text' ? 'TEXT' : 'TXT';
          const ts = data.processed_at || data.uploaded_at;
          setViewing({
            id: f.id,
            name: data.original_name || f.title,
            type,
            chunks: data.chunk_count || 0,
            status: data.status || f.status,
            size: data.file_size_kb ? data.file_size_kb + ' KB' : '—',
            date: ts ? new Date(ts).toLocaleString('pt-BR') : '—',
            detail: data,
          });
        })
        .catch((e) => toast({ title: 'Falha ao abrir documento', msg: e.message, kind: 'error' }))
        .finally(() => setOpening(null));
      return;
    }

    if ((f.kind === 'contexto' || f.kind === 'diretriz') && window.ContextEditModal) {
      setOpening(ref);
      DataLoader.directContexts()
        .then(() => {
          const c = (Data.directContexts || []).find((x) => x.id === f.id);
          if (c) setEditingCtx(c);
          else toast({ title: 'Contexto não encontrado', kind: 'info' });
        })
        .catch((e) => toast({ title: 'Falha ao abrir contexto', msg: e.message, kind: 'error' }))
        .finally(() => setOpening(null));
      return;
    }

    // Fallback: fonte sem modal próprio aqui → navega (a pesquisa já ficou salva
    // em window.__kbSearchState e é restaurada quando o admin voltar pra cá).
    if (!f.route) return;
    window.__kbOpen = { kind: f.kind, id: f.id, tab: f.tab, ts: Date.now() };
    if (window.appNavigate) window.appNavigate(f.route);
  };

  const kindMeta = {
    documento:     { icon: 'fa-file-lines', label: 'Documento', cls: 'b-bl' },
    contexto:      { icon: 'fa-lightbulb',  label: 'Contexto direto', cls: 'b-or' },
    diretriz:      { icon: 'fa-route',      label: 'Diretriz', cls: 'b-bl' },
    system_prompt: { icon: 'fa-terminal',   label: 'System prompt', cls: 'b-mut' },
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1><span className="h1-icon"><i className="fas fa-magnifying-glass"></i></span> Buscar na base</h1>
          <p className="sub">
            Pergunte em linguagem natural <strong>onde</strong> um conteúdo ou instrução está cadastrado —
            a IA localiza a fonte e o link pra você editar. Ex.: "onde está o valor da mensalidade?",
            "onde configurei a regra de cancelamento?".
          </p>
        </div>
      </div>

      <div className="card">
        <div className="row gap-sm">
          <input
            className="input"
            style={{ flex: 1 }}
            placeholder="Onde está…? Ex.: onde fala do reajuste de 5,15%?"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') run(); }}
            autoFocus
          />
          <button className="btn btn-primary" onClick={run} disabled={busy}>
            {busy ? <><i className="fas fa-circle-notch fa-spin"></i> Buscando…</> : <><i className="fas fa-magnifying-glass"></i> Buscar</>}
          </button>
        </div>
      </div>

      {busy && (
        <div className="card" style={{ textAlign: 'center', color: 'var(--t3)', padding: 28 }}>
          <i className="fas fa-circle-notch fa-spin" style={{ fontSize: 20 }}></i>
          <p style={{ marginTop: 10, fontSize: 13 }}>A IA está localizando onde isso está na base…</p>
        </div>
      )}

      {result && !busy && (
        <>
          <div className="card" style={{ borderLeft: '3px solid var(--or)' }}>
            <div className="row gap-sm" style={{ alignItems: 'flex-start' }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--og)', color: 'var(--or)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <i className="fas fa-wand-magic-sparkles"></i>
              </div>
              <div style={{ fontSize: 13.5, color: 'var(--t1)', lineHeight: 1.6, flex: 1, whiteSpace: 'pre-wrap' }}>
                {result.resposta}
              </div>
            </div>
          </div>

          {result.fontes && result.fontes.length > 0 ? (
            <div>
              <div style={{ margin: '4px 2px 8px', fontSize: 11.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em', color: 'var(--t3)' }}>
                Fontes encontradas ({result.fontes.length}) — clique pra editar
              </div>
              {result.fontes.map((f, i) => {
                const m = kindMeta[f.kind] || kindMeta.documento;
                const showStatus = f.status && f.status !== 'ativo' && f.status !== 'indexed';
                return (
                  <div
                    key={f.ref || i}
                    className="card kb-result"
                    style={{ cursor: 'pointer', padding: 0, marginBottom: 10 }}
                    onClick={() => openSource(f)}
                  >
                    <div style={{ display: 'flex', alignItems: 'stretch', gap: 4 }}>
                      <div style={{ flex: 1, minWidth: 0, padding: '14px 16px' }}>
                        <div className="row gap-sm" style={{ flexWrap: 'wrap', marginBottom: 8 }}>
                          <span className={'badge ' + m.cls}><i className={'fas ' + m.icon}></i> {m.label}</span>
                          {showStatus && <span className="badge b-mut">{f.status}</span>}
                        </div>
                        <div style={{ fontWeight: 600, fontSize: 14.5, color: 'var(--t1)', marginBottom: 6, lineHeight: 1.35 }}>
                          {f.title}
                        </div>
                        <div style={{ fontSize: 12.5, color: 'var(--t3)', lineHeight: 1.5, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                          {String(f.snippet || '').replace(/#+\s*/g, '').trim()}
                        </div>
                        <div style={{ fontSize: 11.5, color: 'var(--t2)', marginTop: 10 }}>
                          <i className="fas fa-location-arrow" style={{ marginRight: 5, color: 'var(--or)' }}></i>
                          Editar em: <strong>{f.tab}</strong>
                        </div>
                      </div>
                      <button
                        className="btn btn-soft btn-sm"
                        title="Abrir editor"
                        onClick={(e) => { e.stopPropagation(); openSource(f); }}
                        disabled={opening === (f.ref || `${f.kind}:${f.id}`)}
                        style={{ alignSelf: 'center', marginRight: 14, flexShrink: 0, whiteSpace: 'nowrap' }}
                      >
                        {opening === (f.ref || `${f.kind}:${f.id}`)
                          ? <><i className="fas fa-circle-notch fa-spin"></i> Abrindo…</>
                          : <>Editar <i className="fas fa-arrow-right"></i></>}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="card" style={{ textAlign: 'center', color: 'var(--t3)', padding: 20 }}>
              <i className="fas fa-circle-info"></i>
              <p style={{ marginTop: 8, fontSize: 12.5 }}>Nenhuma fonte específica retornada. Tente outras palavras-chave.</p>
            </div>
          )}
        </>
      )}

      {/* Modais abertos NA PRÓPRIA página de busca — ao fechar, a pesquisa segue ativa. */}
      {viewing && window.FileViewModal && (
        <window.FileViewModal file={viewing} onClose={() => setViewing(null)} />
      )}
      {editingCtx && window.ContextEditModal && (
        <window.ContextEditModal
          context={editingCtx}
          onClose={() => setEditingCtx(null)}
          onSaved={() => setEditingCtx(null)}
        />
      )}
    </div>
  );
}

window.ScreenKbSearch = ScreenKbSearch;
