// ============================================================================
// public/screens/kb.jsx — Knowledge Base (Phase 6A)
// ============================================================================

function KnowledgeBaseScreen() {
  const [colls, setColls]         = React.useState(null);
  const [activeColl, setActive]   = React.useState(null); // full collection object
  const [docs, setDocs]           = React.useState([]);
  const [showCreate, setShowCreate] = React.useState(false);
  const [showAddDoc, setShowAddDoc] = React.useState(false);
  const [showQuery, setShowQuery] = React.useState(false);

  const load = React.useCallback(async () => {
    const r = await VoaisAPI.get("/api/kb");
    if (r.ok && r.data?.ok) setColls(r.data.collections);
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const openCollection = async (id) => {
    const r = await VoaisAPI.get("/api/kb/" + id);
    if (r.ok && r.data?.ok) { setActive(r.data.collection); setDocs(r.data.documents); }
  };

  const deleteDoc = async (collId, docId) => {
    if (!confirm("Delete this document and all its chunks?")) return;
    await VoaisAPI.del("/api/kb/" + collId + "/documents/" + docId);
    openCollection(collId);
  };

  const deleteColl = async (id) => {
    if (!confirm("Delete this collection and ALL its documents?")) return;
    await VoaisAPI.del("/api/kb/" + id);
    setActive(null); load();
  };

  if (colls === null) return <DashboardSkeleton/>;

  // Collection detail view
  if (activeColl) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Btn kind="ghost" size="sm" icon={<I.arrow_left size={13}/>} onClick={() => { setActive(null); load(); }}>Collections</Btn>
          <div style={{ width: 1, height: 20, background: "var(--line)" }}/>
          <span style={{ fontSize: 16, fontWeight: 600 }}>{activeColl.name}</span>
          <Badge tone="blue">{activeColl.total_docs} docs</Badge>
          <Badge tone="gray">{activeColl.total_chunks} chunks</Badge>
          <div style={{ flex: 1 }}/>
          <Btn kind="ghost" size="sm" icon={<I.search size={13}/>} onClick={() => setShowQuery(true)}>Test query</Btn>
          <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShowAddDoc(true)}>Add document</Btn>
        </div>

        {activeColl.description && <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{activeColl.description}</div>}

        {/* Documents table */}
        <Card padded={false}>
          <table className="data-table" style={{ width: "100%", fontSize: 13 }}>
            <thead><tr>
              <th style={{ paddingLeft: 16 }}>Document</th><th>Type</th><th>Size</th><th>Status</th><th>Chunks</th><th>Added</th><th></th>
            </tr></thead>
            <tbody>
              {docs.map(d => (
                <tr key={d.id}>
                  <td style={{ paddingLeft: 16 }}>
                    <div style={{ fontWeight: 500 }}>{d.name}</div>
                    <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{d.code}</div>
                  </td>
                  <td><Badge tone="gray">{d.type}</Badge></td>
                  <td className="tabular">{formatBytes(d.size_bytes)}</td>
                  <td><Badge tone={d.index_status === "indexed" ? "green" : d.index_status === "failed" ? "red" : "yellow"}>{d.index_status}</Badge></td>
                  <td className="tabular">{d.chunks_count}</td>
                  <td style={{ fontSize: 11, color: "var(--ink-3)" }}>{new Date(d.created_at).toLocaleDateString("en-IN", { day: "numeric", month: "short" })}</td>
                  <td><Btn kind="ghost" size="sm" onClick={() => deleteDoc(activeColl.id, d.id)}><I.trash size={12}/></Btn></td>
                </tr>
              ))}
              {docs.length === 0 && <tr><td colSpan={7} style={{ textAlign: "center", padding: 32, color: "var(--ink-3)" }}>No documents yet. Add one to get started.</td></tr>}
            </tbody>
          </table>
        </Card>

        {/* Add document modal */}
        {showAddDoc && <AddDocModal collId={activeColl.id} onClose={() => setShowAddDoc(false)} onAdded={() => { setShowAddDoc(false); openCollection(activeColl.id); }}/>}

        {/* Query tester modal */}
        {showQuery && <QueryTestModal collId={activeColl.id} onClose={() => setShowQuery(false)}/>}
      </div>
    );
  }

  // Collection list view
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap-grid)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Badge tone="blue" dot>{colls.length} collections</Badge>
        <div style={{ flex: 1 }}/>
        <Btn kind="primary" size="sm" icon={<I.plus size={13}/>} onClick={() => setShowCreate(true)}>New collection</Btn>
      </div>

      {colls.length === 0 && (
        <Card>
          <div style={{ padding: "40px 24px", textAlign: "center", maxWidth: 520, margin: "0 auto" }}>
            <div style={{ width: 64, height: 64, borderRadius: 16, margin: "0 auto 20px", display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)" }}><I.kb size={28}/></div>
            <h2 style={{ fontSize: 22, fontWeight: 600, margin: "14px 0 10px" }}>Knowledge Base</h2>
            <p style={{ color: "var(--ink-3)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 20px" }}>
              Upload product docs, FAQs, and guides. Your AI agents will use this knowledge to answer questions during calls.
            </p>
            <Btn kind="primary" icon={<I.plus size={14}/>} onClick={() => setShowCreate(true)}>Create collection</Btn>
          </div>
        </Card>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: "var(--gap-grid)" }}>
        {colls.map(c => (
          <Card key={c.id} padded={false}>
            <div style={{ padding: 16, cursor: "pointer" }} onClick={() => openCollection(c.id)}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <I.kb size={18} style={{ color: "var(--accent)" }}/>
                <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, flex: 1 }}>{c.name}</h3>
              </div>
              {c.description && <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>{c.description}</div>}
              <div style={{ display: "flex", gap: 12, marginTop: 12, fontSize: 12, color: "var(--ink-3)" }}>
                <span>{c.total_docs} docs</span>
                <span>{c.total_chunks} chunks</span>
                <span>{formatBytes(c.total_size_bytes)}</span>
              </div>
            </div>
            <div style={{ padding: "0 16px 12px", display: "flex", gap: 8 }}>
              <Btn kind="primary" size="sm" style={{ flex: 1 }} onClick={() => openCollection(c.id)}>Open</Btn>
              <Btn kind="ghost" size="sm" onClick={() => deleteColl(c.id)}><I.trash size={13}/></Btn>
            </div>
          </Card>
        ))}
      </div>

      {showCreate && (
        <Modal title="New collection" onClose={() => setShowCreate(false)} width={460}>
          <CreateCollForm onCreated={(id) => { setShowCreate(false); load(); openCollection(id); }}/>
        </Modal>
      )}
    </div>
  );
}

function CreateCollForm({ onCreated }) {
  const [name, setName] = React.useState(""); const [desc, setDesc] = React.useState(""); const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!name.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/kb", { name, description: desc || null }); setSub(false); if (r.ok) onCreated(r.data.collectionId); };
  return (<div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
    <Field label="Collection name *"><input className="input" autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Mercedes GLE Product Sheets"/></Field>
    <Field label="Description"><textarea className="textarea" rows={2} value={desc} onChange={e => setDesc(e.target.value)} placeholder="What documents will this contain?"/></Field>
    <Btn kind="primary" onClick={submit} disabled={sub || !name.trim()}>{sub ? "Creating..." : "Create"}</Btn>
  </div>);
}

function AddDocModal({ collId, onClose, onAdded }) {
  const [name, setName] = React.useState(""); const [type, setType] = React.useState("txt"); const [url, setUrl] = React.useState(""); const [sub, setSub] = React.useState(false);
  const submit = async () => { if (!name.trim()) return; setSub(true); const r = await VoaisAPI.post("/api/kb/" + collId + "/documents", { name, type, source_url: url || null }); setSub(false); if (r.ok) onAdded(); else alert(r.data?.msg || "Failed."); };
  return (<Modal title="Add document" onClose={onClose} width={460}>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Field label="Document name *"><input className="input" autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. GLE_brochure.pdf"/></Field>
      <Field label="Type"><select className="select" value={type} onChange={e => setType(e.target.value)}><option value="pdf">PDF</option><option value="docx">DOCX</option><option value="txt">TXT</option><option value="md">Markdown</option><option value="csv">CSV</option><option value="url">URL</option><option value="html">HTML</option></select></Field>
      {type === "url" && <Field label="Source URL"><input className="input" value={url} onChange={e => setUrl(e.target.value)} placeholder="https://..."/></Field>}
      <div style={{ fontSize: 12, color: "var(--ink-3)" }}>File upload will be available once storage is configured. For now, add document metadata and upload via the API.</div>
      <Btn kind="primary" onClick={submit} disabled={sub || !name.trim()}>{sub ? "Adding..." : "Add document"}</Btn>
    </div>
  </Modal>);
}

function QueryTestModal({ collId, onClose }) {
  const [query, setQuery] = React.useState(""); const [results, setResults] = React.useState(null); const [loading, setL] = React.useState(false);
  const search = async () => { if (!query.trim()) return; setL(true); const r = await VoaisAPI.post("/api/kb/query", { collection_id: collId, query, limit: 5 }); setL(false); if (r.ok) setResults(r.data.results); };
  return (<Modal title="Test RAG query" onClose={onClose} width={580}>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", gap: 8 }}><input className="input" style={{ flex: 1 }} placeholder="Ask a question..." value={query} onChange={e => setQuery(e.target.value)} onKeyDown={e => { if (e.key==="Enter") search(); }}/><Btn kind="primary" onClick={search} disabled={loading}>{loading ? "..." : "Search"}</Btn></div>
      {results && results.length === 0 && <div style={{ color: "var(--ink-3)", fontSize: 13 }}>No matching chunks found.</div>}
      {results && results.map((r, i) => (
        <div key={i} style={{ padding: "10px 12px", background: "var(--surface-2)", borderRadius: 8, fontSize: 13 }}>
          <div style={{ fontWeight: 500, marginBottom: 4 }}>{r.document_name} — Chunk #{r.chunk_index}</div>
          <div style={{ color: "var(--ink-3)", lineHeight: 1.5 }}>{r.content?.slice(0, 300)}{r.content?.length > 300 ? "..." : ""}</div>
        </div>
      ))}
    </div>
  </Modal>);
}

function formatBytes(b) { if (!b || b === 0) return "0 B"; const k = 1024; const s = ["B","KB","MB","GB"]; const i = Math.floor(Math.log(b)/Math.log(k)); return (b/Math.pow(k,i)).toFixed(1)+" "+s[i]; }

window.KnowledgeBaseScreen = KnowledgeBaseScreen;
