import { useState, useRef, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext';
import { useLocation } from 'react-router-dom';
const STORAGE_KEY = 'admin_chat_session_id';
const FAQ_DATA = {
"Document Review": [
{ q: "How do I review a document?", a: "From the Admin Dashboard, click on any user. You'll see their uploaded documents. Click Approve or Reject and leave a note if needed." },
{ q: "What happens when I reject a document?", a: "The document status changes to Rejected and the user is notified. They can upload a corrected version." },
{ q: "How do I upload admin documents for a user?", a: "Go to the user's detail page β Returns for Review tab β click '+ Upload Document'." }
],
"User Management": [
{ q: "How do I see user details?", a: "Click any user in the Admin Dashboard table to open their full detail view." },
{ q: "Can I add another admin?", a: "Super Admins can only be created via the backend script `create_super_admin.py`." }
],
"Notifications": [
{ q: "How are users notified?", a: "Users receive emails on signup, document submission, and when you approve or reject their documents." }
]
};
const CATEGORY_ICONS = { "Document Review": "π", "User Management": "π₯", "Notifications": "π" };
const escapeHtml = (unsafe) => {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
const formatMessage = (text) => {
if (!text) return '';
let safeText = escapeHtml(text);
return safeText
.replace(/\*\*(.*?)\*\*/g, '$1')
.replace(/\*(.*?)\*/g, '$1')
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => {
let decodedUrl = url.replace(/'/g, "'").replace(/"/g, '"').replace(/&/g, '&');
if (decodedUrl.toLowerCase().trim().startsWith('javascript:')) {
return escapeHtml(match);
}
return `${text}`;
})
.replace(/\n/g, '
');
};
export default function AdminChatbot() {
const { user, authFetch } = useAuth();
const location = useLocation();
const [isOpen, setIsOpen] = useState(false);
const [view, setView] = useState('menu');
const [activeCategory, setActiveCategory] = useState(null);
const [inputText, setInputText] = useState("");
const [menuInput, setMenuInput] = useState("");
const [isTyping, setIsTyping] = useState(false);
const [pendingBulk, setPendingBulk] = useState(null); // bulk action awaiting confirmation
const chatEndRef = useRef(null);
const [messages, setMessages] = useState([]);
const [sessionId, setSessionId] = useState(null);
useEffect(() => {
if (!user) return;
async function loadHistory() {
const savedSession = localStorage.getItem(STORAGE_KEY);
const url = savedSession ? `/api/chatbot/history?session_id=${savedSession}` : '/api/chatbot/history';
try {
const res = await authFetch(url);
if (res.ok) {
const data = await res.json();
setSessionId(data.session_id);
localStorage.setItem(STORAGE_KEY, data.session_id);
const loaded = data.messages.map(m => ({
type: m.role === 'user' ? 'user' : 'bot',
role: m.role,
text: m.content || '',
...m
})).filter(m => m.role === 'user' || m.role === 'assistant');
setMessages(loaded);
}
} catch (e) {
console.error("Failed to load admin chat history", e);
}
}
loadHistory();
}, [authFetch, user]);
useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]);
const clearHistory = () => {
setMessages([]);
setSessionId(null);
localStorage.removeItem(STORAGE_KEY);
};
// ββ System overview βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const handleAdminStatusCheck = async () => {
sendMessage('Give me a system overview.');
};
// ββ Bulk action executor with confirmation ββββββββββββββββββββββββββββββββ
const executeBulkAction = async (action) => {
if (!action) return;
try {
const res = await authFetch('/api/chatbot/admin-bulk-action', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...action, confirm: true }),
});
if (res.ok) {
const data = await res.json();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: `β
${data.message}` }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Action failed. Please try from the user detail page.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error during bulk action.' }]);
} finally {
setPendingBulk(null);
}
};
// ββ Send message (with full history for memory) βββββββββββββββββββββββββββ
const sendMessage = useCallback(async (text, overrideMessages) => {
const userMsg = { type: 'user', role: 'user', text };
const allMessages = [...(overrideMessages ?? messages), userMsg];
setMessages(allMessages);
setInputText("");
setMenuInput("");
setView('chat');
setIsTyping(true);
try {
const res = await authFetch('/api/chatbot/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
stream: false,
session_id: sessionId,
message: text,
}),
});
if (res.ok) {
const data = await res.json();
const replyText = data.content || "Sorry, I couldn't understand that.";
// Check if response contains a bulk_action JSON block
let jsonStr = replyText;
const mdMatch = replyText.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
if (mdMatch) {
jsonStr = mdMatch[1];
} else {
const firstIdx = replyText.indexOf('{');
const lastIdx = replyText.lastIndexOf('}');
if (firstIdx !== -1 && lastIdx !== -1) {
jsonStr = replyText.substring(firstIdx, lastIdx + 1);
}
}
if (jsonStr.includes('"bulk_action"')) {
try {
const parsed = JSON.parse(jsonStr);
if (parsed.bulk_action) {
setPendingBulk(parsed.bulk_action);
const cleanText = replyText.replace(jsonStr, '').replace(/```(?:json)?|```/g, '').trim();
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: cleanText || "I can do that. Please confirm below." }]);
setIsTyping(false);
return;
}
} catch (e) {
console.error("Failed to parse JSON:", e, jsonStr);
/* not valid JSON, render as text */
}
}
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: replyText }]);
} else {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Having trouble connecting. Please try again.' }]);
}
} catch {
setMessages(prev => [...prev, { type: 'bot', role: 'assistant', text: 'Network error. Please try again.' }]);
} finally {
setIsTyping(false);
}
}, [messages, authFetch, sessionId]);
const handleSendMessage = (e) => { e.preventDefault(); if (inputText.trim()) sendMessage(inputText.trim()); };
const handleMenuAsk = (e) => { e.preventDefault(); if (menuInput.trim()) sendMessage(menuInput.trim(), []); };
const askFaq = (faq) => {
setMessages(prev => [...prev, { type: 'user', text: faq.q }, { type: 'bot', text: faq.a }]);
setView('chat');
};
if (!user || (user.role !== 'admin' && user.role !== 'super_admin') || !location.pathname.startsWith('/admin')) return null;
return (
<>
{isOpen && (
What do you need today?
Admin tools & shortcuts
)}