import { useCallback, useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { deleteUserAdmin, getKbStatus, listUsersAdmin, mergeKbCsvUpload } from '../api/admin' import { clearAdminSession, getStoredAdmin } from '../auth/adminStorage' import ComsatsLogo from '../components/ComsatsLogo' const PAGE_SIZE = 15 function initialsFromProfile(fullName, email) { const n = (fullName || '').trim() if (n) { const parts = n.split(/\s+/).filter(Boolean) if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase() return n.slice(0, 2).toUpperCase() } const local = (email || '').split('@')[0] || '?' return local.slice(0, 2).toUpperCase() } function shortUserId(id) { if (!id) return '—' if (id.length <= 14) return id return `${id.slice(0, 8)}…${id.slice(-4)}` } export default function AdminPanel() { const navigate = useNavigate() const [admin] = useState(() => getStoredAdmin()) const [section, setSection] = useState('kb') const [page, setPage] = useState(1) const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [usersError, setUsersError] = useState('') const [deletingId, setDeletingId] = useState(null) const [copiedId, setCopiedId] = useState(null) const [kbStatus, setKbStatus] = useState(null) const [kbLoading, setKbLoading] = useState(true) const [kbFile, setKbFile] = useState(null) const [kbUploading, setKbUploading] = useState(false) const [kbError, setKbError] = useState('') const [kbSuccess, setKbSuccess] = useState('') const loadKb = useCallback(async () => { setKbError('') setKbLoading(true) try { setKbStatus(await getKbStatus()) } catch (e) { setKbError(e.message || 'Failed to load knowledge base status') setKbStatus(null) } finally { setKbLoading(false) } }, []) useEffect(() => { loadKb() }, [loadKb]) const loadUsers = useCallback(async () => { setUsersError('') setLoading(true) try { const res = await listUsersAdmin(page, PAGE_SIZE) setData(res) } catch (e) { setUsersError(e.message || 'Failed to load users') setData(null) } finally { setLoading(false) } }, [page]) useEffect(() => { loadUsers() }, [loadUsers]) function logout() { clearAdminSession() navigate('/admin/login', { replace: true }) } async function copyUserId(userId) { try { await navigator.clipboard.writeText(userId) setCopiedId(userId) window.setTimeout(() => setCopiedId(null), 2000) } catch { setCopiedId(null) } } async function onDelete(userId, email) { if (!window.confirm(`Remove ${email} from the directory? All of their conversations will be permanently deleted.`)) return setDeletingId(userId) setUsersError('') try { await deleteUserAdmin(userId) await loadUsers() } catch (e) { setUsersError(e.message || 'Delete failed') } finally { setDeletingId(null) } } const pages = data?.pages ?? 0 const total = data?.total ?? 0 async function onKbMergeUpload(e) { e.preventDefault() if (!kbFile) return setKbError('') setKbSuccess('') setKbUploading(true) const fileRef = kbFile try { const res = await mergeKbCsvUpload(() => { const fd = new FormData() fd.append('file', fileRef) return fd }) setKbSuccess( `${res.message} Added ${res.rows_merged ?? 0} rows to the index. File stored as ${res.saved_as ?? 'upload'}.`, ) setKbFile(null) const input = document.getElementById('admin-kb-merge-csv') if (input) input.value = '' await loadKb() } catch (err) { setKbError(err.message || 'Upload failed') } finally { setKbUploading(false) } } const tabBtn = 'rounded-lg px-4 py-2 text-[13px] font-semibold transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-purple focus-visible:ring-offset-2' const tabActive = 'bg-white text-comsats-purple shadow-sm ring-1 ring-slate-200/90' const tabIdle = 'text-slate-600 hover:bg-white/60 hover:text-slate-900' return (

CUI Connect

Administration

{admin?.email ?? 'Signed in'}

{section === 'kb' ? (

Knowledge base

Update the assistant's retrieval index by uploading FAQ-style CSV data. Each upload is embedded and merged into the live FAISS index without a full rebuild.

Retriever

{kbLoading ? '…' : kbStatus?.retriever_ready ? 'Operational' : 'Unavailable'}

{kbLoading ? 'Checking status' : kbStatus?.retriever_ready ? 'Ready for queries' : 'Check server logs'}

Vectors

{kbLoading ? '…' : kbStatus?.vector_count != null ? kbStatus.vector_count.toLocaleString() : '—'}

Documents in FAISS index

Upload history

{kbLoading ? '…' : (kbStatus?.uploaded_csv_count ?? kbStatus?.uploaded_csv_files?.length ?? 0)}

CSV files on disk

Index bundle

{kbLoading ? '…' : kbStatus?.index_on_disk ? 'Present' : 'Missing'}

Saved under configured path

Merge new content

  1. Prepare a UTF-8 CSV in the same column layout as your existing FAQ knowledge.
  2. Select the file below — only .csv up to 25 MB.
  3. Confirm merge; rows are embedded and appended via merge_from.
{kbError ? (
{kbError}
) : null} {kbSuccess ? (
{kbSuccess}
) : null}
setKbFile(ev.target.files?.[0] ?? null)} className="mx-auto block max-w-full cursor-pointer text-[13px] text-slate-800 file:mr-4 file:cursor-pointer file:rounded-xl file:border-0 file:bg-comsats-purple file:px-4 file:py-2.5 file:text-[13px] file:font-semibold file:text-white file:shadow-sm hover:file:brightness-110" />

{kbFile ? ( {kbFile.name} ) : ( 'Choose a file or drag into the file picker (browser dependent)' )}

{kbStatus && !kbLoading ? (
Technical paths & files
FAISS directory
{kbStatus.index_path}
Upload directory
{kbStatus.kb_upload_dir}
Bundled base CSVs
{kbStatus.base_csv_files?.length ? kbStatus.base_csv_files.join(', ') : 'None detected'}
Uploaded CSV filenames
{kbStatus.uploaded_csv_files?.length ? kbStatus.uploaded_csv_files.join(', ') : 'None yet'}
) : kbLoading ? (

Loading knowledge base status…

) : null}
) : (

Registered users

{total.toLocaleString()} {total === 1 ? 'account' : 'accounts'} {pages > 1 ? ` · Page ${page} of ${pages}` : ''}

{usersError ? (
{usersError}
) : null}
{loading ? ( ) : !data?.items?.length ? ( ) : ( data.items.map((row, idx) => ( )) )}
# Member User ID Chats Actions
Loading directory…
No registered users yet.
{(page - 1) * PAGE_SIZE + idx + 1}
{initialsFromProfile(row.full_name, row.email)}

{row.full_name?.trim() || '—'}

{row.email}

{shortUserId(row.user_id)}
{(row.chat_count ?? 0).toLocaleString()}
{pages > 1 ? ( ) : null}
)}
) }