import React, { useState, useEffect, useRef, useCallback } from 'react'; import { StatusBadge } from './Badges'; import { api, NexusMarkdown, getFileIcon, getStorageKey, useMentions, MentionOverlay, RichEditor, useTheme, useNotification } from '@nexus/shared'; import type { Ticket, Message } from '@nexus/shared'; import styles from './ThreadView.module.css'; import { ArrowLeft, Send, Paperclip, Sparkles, Maximize2, RefreshCcw, Loader2, Trash2, BookOpen, Download } from 'lucide-react'; interface ThreadViewProps { ticket: Ticket; onBack: () => void; onNavigate?: (ticket: { id: string }) => void; onNavigateArticle?: (articleId: string) => void; } export const ThreadView: React.FC = ({ ticket: initialTicket, onBack, onNavigate, onNavigateArticle }) => { const { theme } = useTheme(); const { alert, confirm } = useNotification(); const [ticket, setTicket] = useState(initialTicket); const [messages, setMessages] = useState([]); const [newMessage, setNewMessage] = useState(""); const [sending, setSending] = useState(false); const [currentUser, setCurrentUser] = useState<{ id: string, full_name: string } | null>(null); // Description Edit State const [isEditingDesc, setIsEditingDesc] = useState(false); const [descDraft, setDescDraft] = useState(initialTicket.description); const [savingDesc, setSavingDesc] = useState(false); const [isUploading, setIsUploading] = useState(false); // Feedback States const [ratingDraft, setRatingDraft] = useState(ticket.rating || null); const [hoverRating, setHoverRating] = useState(null); const [commentDraft, setCommentDraft] = useState(""); const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false); const [showReopenModal, setShowReopenModal] = useState(false); const [reopenReason, setReopenReason] = useState(""); const [isReopening, setIsReopening] = useState(false); // AI Intensity States const [isRegeneratingSummary, setIsRegeneratingSummary] = useState(false); const [isEscalating, setIsEscalating] = useState(false); const [historyEvents, setHistoryEvents] = useState([]); const [showConfirmEscalate, setShowConfirmEscalate] = useState(false); // Sidebar States const [isSidebarOpen, setIsSidebarOpen] = useState(false); const [isLeftSidebarOpen, setIsLeftSidebarOpen] = useState(false); const [forbidden, setForbidden] = useState(false); const [sidebarWidth, setSidebarWidth] = useState(400); const [isResizing, setIsResizing] = useState(false); const [sidebarTab, setSidebarTab] = useState<'messages' | 'files' | 'history'>('messages'); const { filteredUsers, showMentionList, selectedMentionIndex, setSelectedMentionIndex, cursorPos, handleInputChange, getMentionText, closeMentions } = useMentions({ workspaceId: ticket?.workspace_id }); const bottomRef = useRef(null); const fileInputRef = useRef(null); const isRefreshing = useRef(false); const [isLoading, setIsLoading] = useState(false); const refreshData = useCallback(async (bypassCache = false) => { if (isRefreshing.current) return; isRefreshing.current = true; setIsLoading(true); const watchdog = setTimeout(() => { // Release the refresh lock so users can retry after a hung request. // Without this, isRefreshing stays true indefinitely if the request never // resolves, silently blocking every subsequent manual refresh. setIsLoading(false); isRefreshing.current = false; }, 30000); try { const ticketId = initialTicket.id; const ticketUrl = `tickets/${ticketId}/${bypassCache ? '?bypass_cache=true' : ''}`; const [ticketResp, messagesResp, auditResp] = await Promise.all([ api.get(ticketUrl), api.get(`tickets/${ticketId}/messages/`), api.get(`tickets/${ticketId}/audit/`) ]); setTicket(ticketResp.data); setDescDraft(ticketResp.data.description); setMessages(messagesResp.data); // Transform raw audit logs into UI-friendly history events const rawLogs = auditResp.data; const auditEvents = rawLogs.map((log: any) => { let label = log.action.toUpperCase(); let icon = '📝'; let detail = `Action performed by ${log.actor_name}`; if (log.action === 'create') { icon = '🎫'; label = 'INCIDENT LOGGED'; detail = 'Incident initialized via portal.'; } else if (log.action === 'escalation') { icon = '🚨'; label = 'CRITICAL ESCALATION'; detail = 'Priority elevated to P0 for lead intervention.'; } else if (log.action === 'update' && log.new_value?.status === 'RESOLVED') { icon = '✅'; label = 'RESOLVED'; detail = 'Agent has finalized the resolution.'; } else if (log.action === 'update' && log.new_value?.status === 'ACKNOWLEDGED') { icon = '🛡️'; label = 'ACKNOWLEDGED'; detail = 'Technical specialist has claimed this ticket.'; } else if (log.action === 'update' && log.new_value?.status === 'IN_PROGRESS') { icon = '⚙️'; label = 'IN PROGRESS'; detail = 'Active investigation is underway.'; } else if (log.action === 'update' && log.new_value?.priority) { icon = '⚡'; label = 'PRIORITY CHANGE'; detail = `Priority adjusted to ${log.new_value.priority}.`; } else if (log.action === 'update' && log.new_value?.assigned_to) { icon = '👥'; label = 'ASSIGNMENT'; detail = `Assigned to ${log.new_value.assigned_to_name || 'Technical Specialist'}.`; } else if (log.action === 'update' && log.new_value?.title) { icon = '✏️'; label = 'TITLE UPDATED'; detail = 'Subject was refined for clarity.'; } else if (log.action === 'reopen') { icon = '🔄'; label = 'REOPENED'; detail = log.new_value?.reason || 'Resumed for further review.'; } return { id: log.id, time: log.created_at, label, detail, icon }; }); const messageEvents = (messagesResp.data || []).map((m: any) => { const isCustomer = m.sender_role?.toLowerCase().includes('customer'); return { id: m.id, time: m.created_at, label: isCustomer ? 'CLIENT MESSAGE' : 'AGENT RESPONSE', detail: m.content.length > 100 ? m.content.substring(0, 100) + '...' : m.content, icon: isCustomer ? '💬' : '🎧' }; }); const combinedEvents = [...auditEvents, ...messageEvents].sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime() ); setHistoryEvents(combinedEvents); setForbidden(false); } catch (err: any) { console.error("Failed to refresh data", err); if (err.response?.status === 403) { setForbidden(true); } } finally { clearTimeout(watchdog); setIsLoading(false); isRefreshing.current = false; } }, [initialTicket.id]); useEffect(() => { // Standard data fetch on mount, NO force-refresh (bypassCache=false) refreshData(false); const userString = localStorage.getItem(getStorageKey('user')); if (userString) setCurrentUser(JSON.parse(userString)); }, [initialTicket.id]); // ONLY trigger on ID change, ignore refreshData ref to avoid loops // Real-time Event Listener useEffect(() => { const handleLiveEvent = (event: Event) => { const customEvent = event as CustomEvent; const data = customEvent.detail; if (data.event === 'summary_updated' && data.ticket_id === ticket.id) { refreshData(); setIsRegeneratingSummary(false); } else if ((data.event === 'ticket_updated' || data.event === 'new_message') && data.ticket_id === ticket.id) { if (data.event === 'new_message') { setMessages(prev => { if (prev.some(m => m.id === data.message.id)) return prev; return [...prev, data.message]; }); setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 50); } else { refreshData(); } } }; window.addEventListener('nexus-live-event', handleLiveEvent); return () => window.removeEventListener('nexus-live-event', handleLiveEvent); }, [ticket?.id]); // Removed refreshData from dependencies to prevent listener churn loops // Reset state only when navigating to a DIFFERENT ticket ID useEffect(() => { setTicket(initialTicket); setMessages([]); setDescDraft(initialTicket.description); setNewMessage(""); setRatingDraft(initialTicket.rating || null); setIsEditingDesc(false); setShowConfirmEscalate(false); setIsRegeneratingSummary(false); closeMentions(); }, [initialTicket.id]); // ONLY trigger on ID change useEffect(() => { if (isSidebarOpen) { setTimeout(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, 100); } }, [messages, isSidebarOpen, sidebarTab]); // Sidebar Resize Logic const handleMouseDown = useCallback((e: React.MouseEvent) => { e.preventDefault(); setIsResizing(true); }, []); useEffect(() => { const handleMouseMove = (e: MouseEvent) => { if (!isResizing) return; const newWidth = window.innerWidth - e.clientX - 32; if (newWidth > 320 && newWidth < window.innerWidth * 0.5) { setSidebarWidth(newWidth); } }; const handleMouseUp = () => setIsResizing(false); if (isResizing) { document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); document.body.style.cursor = 'col-resize'; } else { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); document.body.style.cursor = 'default'; } return () => { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; }, [isResizing]); // --- MENTION LOGIC --- const handleMentionInput = (e: React.ChangeEvent) => { const val = e.target.value; const position = e.target.selectionStart; setNewMessage(val); handleInputChange(val, position); }; const handleInsertMention = (user: any) => { const textBeforeMention = newMessage.slice(0, cursorPos).replace(/@(\w*)$/, ""); const textAfterMention = newMessage.slice(cursorPos); const mentionText = getMentionText(user); const newValue = textBeforeMention + mentionText + textAfterMention; setNewMessage(newValue); closeMentions(); }; const handleSend = async () => { if (!newMessage.trim() || sending) return; const content = newMessage; const tempId = `temp-${Date.now()}`; const optimisticMsg: any = { id: tempId, content: content, sender_id: currentUser?.id || 'unknown', sender_name: currentUser?.full_name || "You", sender_role: "customer", is_internal: false, created_at: new Date().toISOString(), attachments: [], is_sending: true }; setMessages(prev => [...prev, optimisticMsg]); setNewMessage(""); setSending(true); try { const resp = await api.post(`tickets/${ticket.id}/messages/`, { content, is_internal: false }); setMessages(prev => prev.map(m => m.id === tempId ? resp.data : m)); } catch { setMessages(prev => prev.filter(m => m.id !== tempId)); setNewMessage(content); } finally { setSending(false); } }; const handleSaveDescription = async () => { setSavingDesc(true); try { const resp = await api.patch(`tickets/${ticket.id}/`, { description: descDraft }); setTicket(resp.data); setIsEditingDesc(false); } catch { console.error("Failed to update description"); } finally { setSavingDesc(false); } }; const handleRegenerateSummary = async () => { setIsRegeneratingSummary(true); try { await api.post(`tickets/${ticket.id}/summarize/`); } catch { setIsRegeneratingSummary(false); } }; const handleReopen = async () => { if (!reopenReason.trim()) return; setIsReopening(true); try { await api.post(`tickets/${ticket.id}/reopen/`, { reason: reopenReason }); setReopenReason(""); setShowReopenModal(false); refreshData(); } catch (err) { console.error("Reopen failed", err); } finally { setIsReopening(false); } }; const handleEscalate = async () => { setIsEscalating(true); try { const resp = await api.post(`tickets/${ticket.id}/escalate/`); setTicket(resp.data); setShowConfirmEscalate(false); const messagesResp = await api.get(`tickets/${ticket.id}/messages/`); setMessages(messagesResp.data); } catch { console.error("Escalation failed"); } finally { setIsEscalating(false); } }; const handleSubmitFeedback = async () => { if (!ratingDraft) return; setIsSubmittingFeedback(true); try { const resp = await api.post(`tickets/${ticket.id}/feedback/`, { rating: ratingDraft, comment: commentDraft }); setTicket({ ...ticket, rating: resp.data.rating, feedback_comment: resp.data.comment }); } catch { console.error("Feedback submission failed"); } finally { setIsSubmittingFeedback(false); } }; const handlePaste = async (e: React.ClipboardEvent, isMainDesc: boolean) => { const items = e.clipboardData.items; let fileItem = null; for (let i = 0; i < items.length; i++) { if (items[i].kind === "file") { fileItem = items[i]; break; } } if (fileItem) { e.preventDefault(); const file = fileItem.getAsFile(); if (!file) return; await handleUpload(file, isMainDesc); } }; const handleUpload = async (file: File, isMainDesc: boolean) => { if (file.size > 10 * 1024 * 1024) { alert("File is too large (max 10MB).", { type: 'error', title: 'Upload Restriction' }); return; } setIsUploading(true); const formData = new FormData(); formData.append("file", file); const isImage = file.type.startsWith("image/"); const uploadId = Date.now() % 10000; const placeholder = isImage ? `\n![Uploading ${file.name} (#${uploadId})...]()\n` : `\n[Uploading ${file.name} (#${uploadId})...]()\n`; if (isMainDesc) setDescDraft((curr: string) => curr + placeholder); else setNewMessage((curr: string) => curr + placeholder); try { const resp = await api.post(`tickets/${ticket.id}/attachments/`, formData); const baseUrl = api.defaults.baseURL || ""; const backendBase = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'; const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`; const finalMarkdown = isImage ? `\n![Screenshot](${downloadUrl})\n` : `\n${getFileIcon(file.name)} [${file.name}](${downloadUrl})\n`; if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, finalMarkdown)); else setNewMessage((curr: string) => curr.replace(placeholder, finalMarkdown)); setTicket(curr => ({ ...curr, attachments: [...(curr.attachments || []), resp.data] })); } catch { if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, "")); else setNewMessage((curr: string) => curr.replace(placeholder, "")); } finally { setIsUploading(false); } }; const formatETA = (dateStr: string) => { if (!dateStr) return "PENDING"; const date = new Date(dateStr); return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).toUpperCase(); }; const handleDeleteMessage = async (messageId: string) => { const confirmed = await confirm("Purge this message from your history?", { title: "Purge Message", confirmLabel: "Purge", type: "error", danger: true }); if (!confirmed) return; api.delete(`tickets/${ticket.id}/messages/${messageId}/`).then(() => { setMessages(prev => prev.filter(m => m.id !== messageId)); }).catch(() => { alert("Deletion failed.", { type: 'error', title: 'System Error' }); }); }; const handleDeleteAttachment = async (attachmentId: string) => { const confirmed = await confirm("Permanently remove this asset?", { title: "Remove Asset", confirmLabel: "Remove", type: "error", danger: true }); if (!confirmed) return; try { // Correct endpoint path matches main.py prefix + attachments.py route await api.delete(`tickets/attachments/${attachmentId}/`); setTicket(curr => ({ ...curr, attachments: (curr.attachments || []).filter(a => a.id !== attachmentId) })); setMessages(prev => prev.map(m => ({ ...m, attachments: (m.attachments || []).filter(a => a.id !== attachmentId) }))); } catch (err) { console.error("Asset deletion failed", err); alert("Failed to delete attachment. Please verify permissions.", { type: 'error', title: 'Access Denied' }); } }; const handleFileDownload = async (attId: string, fileName: string) => { try { const response = await api.get(`tickets/attachments/${attId}/download/`, { responseType: 'blob' }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', fileName || 'attachment'); document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); } catch (error) { console.error("Download failed:", error); alert("Authenticated asset download failed. Session may have expired.", { type: 'error', title: 'Download Error' }); } }; if (forbidden) { return (
🛡️

ACCESS RESTRICTED

Your current neural credentials do not permit access to this specific operational thread.

); } if (!ticket) return null; return (
#{ticket.id.slice(0, 8).toUpperCase()}
{ticket.is_escalated && (
ESCALATED
)}

{ticket.title}

{['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && ( )} {!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !ticket.is_escalated && ( )}
TICKET PRIORITY
{ticket.priority?.toUpperCase() || "STANDARD"}
ASSIGNED AGENT
{ticket.assigned_name ? ticket.assigned_name[0] : "N"}
{ticket.assigned_name || "Nexus AI Agent"}
OPERATIONAL STATUS
ESTIMATED RESOLUTION
{formatETA(ticket.expected_resolution_at || "")}
{/* Left Sidebar: Analysis & Context */}
{/* AI Intelligence Summary */} {ticket.status?.toUpperCase() !== 'OPEN' && (
AI Intelligence Summary
{isRegeneratingSummary ? (
Synthesizing neural insights...
) : ticket.summary ? ( ) : (
Neural core is synthesizing high-fidelity resolution steps...
)}
)} {/* Duplicate Alert HUD */} {ticket.status === 'CLOSED' && ticket.duplicate_of_id && (
Duplicate Signal Detected
This incident has been linked to onNavigate?.({ id: ticket.duplicate_of_id! })}>#{ticket.duplicate_of_id.slice(0, 8).toUpperCase()}.
)} {/* Ticket Description Card */}
Ticket details
{!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !isEditingDesc && ( )}
{isEditingDesc ? (
) : (
)}
{/* Resolution Overview (Visible when resolved/closed) */} {(ticket.status === 'RESOLVED' || ticket.status === 'CLOSED' || ticket.resolution_text) && (
Resolution
)} {/* Feedback Section (Conditional) */} {ticket.status === 'RESOLVED' && !ticket.rating && (
How was the resolution?

Your feedback helps us optimize the Nexus neural core.

{[1, 2, 3, 4, 5].map(star => (
setHoverRating(star)} onMouseLeave={() => setHoverRating(null)} onClick={() => setRatingDraft(star)} style={{ cursor: 'pointer', fontSize: 32, transition: 'all 0.2s', transform: (hoverRating || ratingDraft || 0) >= star ? 'scale(1.2)' : 'scale(1)' }} > {(hoverRating || ratingDraft || 0) >= star ? '⭐' : '☆'}
))}