import React, { useState, useRef, useEffect, useCallback } from 'react'; import { Box, Typography, Card, CardContent, CircularProgress, Chip, IconButton, Divider, Alert, LinearProgress, Dialog, DialogTitle, DialogContent, DialogActions, Tooltip, Button, Accordion, AccordionSummary, AccordionDetails, TextField, Avatar, InputAdornment, Paper, } from '@mui/material'; import { ExpandMore as ExpandMoreIcon, Refresh as RefreshIcon, Code as CodeIcon, UnfoldMore as ExpandAllIcon, UnfoldLess as CollapseAllIcon, ContentCopy as CopyIcon, Download as DownloadIcon, PlayArrow as EnableScrollIcon, Pause as DisableScrollIcon, Send as SendIcon, SmartToy as BotIcon, Person as PersonIcon, } from '@mui/icons-material'; import { API_BASE_URI, WEBSOCKET_BASE_URI } from '../constants'; interface ProcessingMessage { type?: string; message: string; progress_percentage?: number; request_id?: string; timestamp: string; stats?: { status: string; number_of_records: number; request_id: string; record_count: number; }; error?: string; isUser?: boolean; } interface PreviewItem { id: string; type: 'json' | 'curl' | 'pdf'; content: string; timestamp: string; isMinified: boolean; pdfUrl?: string; filename?: string; } interface ProcessingStatusProps { fileType: 'Shell' | 'MSAG' | 'Dx Supplementary'; folderPath: string; environment: string; inputType: 'file' | 'json'; json_content?: string; isLoading: boolean; onLoadingChange: (loading: boolean) => void; onStatusChange: (status: 'idle' | 'loading' | 'success' | 'error') => void; triggerProcessing?: boolean; onProcessingComplete?: () => void; } // TypewriterText component for typewriting animation const TypewriterText: React.FC<{ text: string; speed?: number; onComplete?: () => void; isJson?: boolean; isCurl?: boolean; onJsonClick?: () => void; onCurlClick?: () => void; }> = ({ text, speed = 20, onComplete, isJson = false, isCurl = false, onJsonClick, onCurlClick }) => { const [displayText, setDisplayText] = useState(''); const [isComplete, setIsComplete] = useState(false); // Check if this is a Phase or Step heading const isPhaseHeading = text.startsWith("Phase: "); const isStepHeading = text.startsWith("Step: "); useEffect(() => { if (text.length === 0) { setIsComplete(true); onComplete?.(); return; } let index = 0; const timer = setInterval(() => { if (index < text.length) { setDisplayText(text.slice(0, index + 1)); index++; } else { setIsComplete(true); onComplete?.(); clearInterval(timer); } }, speed); return () => clearInterval(timer); }, [text, speed, onComplete]); if (isJson) { const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText; return ( JSON: {preview} {isComplete && ( )} ); } if (isCurl) { const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText; return ( CURL: {preview} {isComplete && ( )} ); } // Render Phase headings with H1 styling during animation if (isPhaseHeading) { return ( {displayText.replace(/^Phase:\s*/, '')} {!isComplete && ( )} ); } // Render Step headings with sub-heading styling during animation if (isStepHeading) { return ( {displayText.replace(/^Step:\s*/, '')} {!isComplete && ( )} ); } return ( {displayText} {!isComplete && ( )} ); }; const ProcessingStatus: React.FC = ({ fileType, folderPath, environment, inputType, json_content, isLoading, onLoadingChange, onStatusChange, triggerProcessing, onProcessingComplete }) => { const [loadStatus, setLoadStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle'); const [accordionExpanded, setAccordionExpanded] = useState(true); const [processingMessages, setProcessingMessages] = useState([]); const [currentProgress, setCurrentProgress] = useState(0); const [finalStats, setFinalStats] = useState(null); const [connectionError, setConnectionError] = useState(null); const [isConnecting, setIsConnecting] = useState(false); const [hasConnected, setHasConnected] = useState(false); const wsRef = useRef(null); // Refs for autoscroll functionality - target the scrollable Box containers const loadingLogRef = useRef(null); const completeLogRef = useRef(null); const errorLogRef = useRef(null); // JSON Dialog state const [jsonDialogOpen, setJsonDialogOpen] = useState(false); const [selectedJsonContent, setSelectedJsonContent] = useState(''); const [isJsonExpanded, setIsJsonExpanded] = useState(true); // Curl Dialog state const [curlDialogOpen, setCurlDialogOpen] = useState(false); const [selectedCurlContent, setSelectedCurlContent] = useState(''); const [isCurlExpanded, setIsCurlExpanded] = useState(true); // Download state const [isDownloading, setIsDownloading] = useState(false); // State for typewriting animation const [completedMessages, setCompletedMessages] = useState>(new Set()); // State for delayed progress and completion updates const [pendingProgressUpdate, setPendingProgressUpdate] = useState(null); const [pendingCompletionData, setPendingCompletionData] = useState<{ stats: ProcessingMessage['stats']; progress: number; } | null>(null); // State to track current phase and step const [currentPhase, setCurrentPhase] = useState(''); const [currentStep, setCurrentStep] = useState(''); // State for auto-scroll functionality const [autoScrollEnabled, setAutoScrollEnabled] = useState(true); // Ref for the main scrollable container const mainContainerRef = useRef(null); // State for preview items (JSON/CURL/PDF) const [previewItems, setPreviewItems] = useState([]); const [activePreviewId, setActivePreviewId] = useState(null); // State for customized processing tooltip const [processingTooltip, setProcessingTooltip] = useState<'Processing' | 'Thinking' | 'Validating'>('Processing'); const [isThinkingMode, setIsThinkingMode] = useState(false); const [isValidatingMode, setIsValidatingMode] = useState(false); // Chat interface state const [userInput, setUserInput] = useState(''); const [hasUserInteracted, setHasUserInteracted] = useState(false); const [isInputDisabled, setIsInputDisabled] = useState(false); // State for JSON delay timer const [jsonDelayTimer, setJsonDelayTimer] = useState(null); // Helper function to add preview item (moved before loadPdfPreview) const addPreviewItem = useCallback((type: 'json' | 'curl' | 'pdf', content: string, pdfUrl?: string, filename?: string) => { const newItem: PreviewItem = { id: `${type}-${Date.now()}-${Math.random()}`, type, content, timestamp: new Date().toLocaleTimeString(), isMinified: false, pdfUrl, filename }; setPreviewItems(prev => { // Minify all existing items and add new item at the beginning (top) const minifiedItems = prev.map(item => ({ ...item, isMinified: true })); return [newItem, ...minifiedItems]; }); setActivePreviewId(newItem.id); }, []); // Function to load PDF from API endpoint (moved before useEffect) const loadPdfPreview = useCallback(async (filename: string) => { try { const response = await fetch(`http://localhost:3000/${filename}`); if (!response.ok) { console.error(`Failed to load PDF: ${response.statusText}`); return; } // Create blob URL for PDF preview const blob = await response.blob(); const pdfUrl = window.URL.createObjectURL(blob); // Add PDF to preview items addPreviewItem('pdf', filename, pdfUrl, filename); } catch (error) { console.error('PDF loading failed:', error); } }, [addPreviewItem]); // Effect to handle processing trigger - allow reconnection for new processing requests useEffect(() => { // Only connect if trigger is true, we're not already connecting, AND user has interacted (typed input) if (!triggerProcessing || isConnecting || !hasUserInteracted) { return; } // Validate required parameters if (!environment || (inputType === 'file' && !folderPath)) { console.warn('Missing required parameters for WebSocket connection'); return; } const connectWebSocket = () => { // Close any existing connection first if (wsRef.current) { wsRef.current.close(); wsRef.current = null; } setIsConnecting(true); try { const ws = new WebSocket(`${WEBSOCKET_BASE_URI}/ws`); wsRef.current = ws; ws.onopen = () => { console.log('WebSocket connected'); setConnectionError(null); setHasConnected(true); setIsConnecting(false); // Send the initial processing request with input_type, environment and filetype const request = { input_type: inputType, environment: environment, filetype: fileType, ...(inputType === 'file' && { foldername: folderPath }) }; ws.send(JSON.stringify(request)); // If input type is json, send the json content as a separate message if (inputType === 'json' && json_content) { ws.send(JSON.stringify({ json: json_content })); } }; ws.onmessage = (event) => { try { const data: ProcessingMessage = JSON.parse(event.data); if (data.error) { setConnectionError(data.error); setLoadStatus('error'); onLoadingChange(false); onStatusChange('error'); return; } // Check for Display messages and load PDF preview if (isDisplayMessage(data.message)) { const filename = extractFilename(data.message); loadPdfPreview(filename); // Don't add Display messages to the processing messages log return; } // Special handling for JSON messages during "Thinking" mode if (isThinkingMode && isValidJSON(data.message)) { // Clear any existing timer if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); } // Set a 1.5 second delay before displaying the message and changing tooltip const timer = setTimeout(() => { // Add the delayed message to processing messages setProcessingMessages(prev => [...prev, data]); // Change tooltip from "Thinking" to "Processing" setIsThinkingMode(false); setProcessingTooltip('Processing'); // Clear the timer setJsonDelayTimer(null); // Handle progress updates if (data.progress_percentage !== undefined) { setPendingProgressUpdate(data.progress_percentage); } }, 1500); // 1.5 seconds delay setJsonDelayTimer(timer); return; // Don't process this message immediately } // Track current phase and step from messages if (data.message.startsWith("Phase: ")) { setCurrentPhase(data.message.replace(/^Phase:\s*/, '')); setCurrentStep(''); // Reset step when new phase starts } else if (data.message.startsWith("Step: ")) { setCurrentStep(data.message.replace(/^Step:\s*/, '')); } // Add message to processing messages (normal flow) setProcessingMessages(prev => [...prev, data]); // Store progress updates for later application (don't apply immediately) if (data.progress_percentage !== undefined) { setPendingProgressUpdate(data.progress_percentage); } // Store completion data ONLY for very specific final completion indicators if (data.type === 'completion' && data.stats) { // This is an explicit completion message with stats from the server setPendingCompletionData({ stats: data.stats, progress: 100 }); } else if (data.message.toLowerCase().trim() === 'data processing completed' || (data.message.toLowerCase().includes('data processing completed') && !data.message.toLowerCase().includes('step') && !data.message.toLowerCase().includes('phase') && data.message.length < 50)) { // Ensure it's a short final message, not a detailed step // Only trigger on the final summary "Data processing Completed" message let recordCount = 0; const recordMatch = data.message.match(/(\d+)\s+records?\s+found/i); if (recordMatch) { recordCount = parseInt(recordMatch[1]); } const stats = { status: 'Complete', number_of_records: recordCount, record_count: recordCount, request_id: Date.now().toString() }; setPendingCompletionData({ stats: stats, progress: 100 }); } } catch (error) { console.error('Error parsing WebSocket message:', error); setConnectionError('Failed to parse server response'); setLoadStatus('error'); onLoadingChange(false); onStatusChange('error'); } }; ws.onerror = (error) => { console.error('WebSocket error:', error); setConnectionError('Failed to connect to processing server. Make sure the backend is running on port 8000.'); setLoadStatus('error'); setIsConnecting(false); onLoadingChange(false); onStatusChange('error'); }; ws.onclose = () => { console.log('WebSocket disconnected'); wsRef.current = null; setIsConnecting(false); }; } catch (error) { console.error('Failed to create WebSocket connection:', error); setConnectionError('Failed to initialize WebSocket connection'); setLoadStatus('error'); setIsConnecting(false); onLoadingChange(false); onStatusChange('error'); } }; // Initialize processing state setLoadStatus('loading'); setAccordionExpanded(true); setProcessingMessages([]); setCurrentProgress(0); setFinalStats(null); setConnectionError(null); setCompletedMessages(new Set()); setCurrentPhase(''); setCurrentStep(''); setHasConnected(false); // Reset connection state for new processing session onLoadingChange(true); onStatusChange('loading'); // Start the connection connectWebSocket(); }, [triggerProcessing, isConnecting, hasConnected, environment, inputType, folderPath, json_content, fileType, onLoadingChange, onStatusChange, isThinkingMode, jsonDelayTimer, loadPdfPreview, hasUserInteracted]); // Include necessary dependencies // Cleanup WebSocket on component unmount useEffect(() => { return () => { if (wsRef.current) { wsRef.current.close(); } // Clear any pending JSON delay timer to prevent memory leaks if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); } }; }, [jsonDelayTimer]); // Effect to handle delayed progress and completion updates useEffect(() => { const lastMessageIndex = processingMessages.length - 1; const isLastMessageComplete = completedMessages.has(lastMessageIndex); const allMessagesComplete = processingMessages.length > 0 && processingMessages.every((_, index) => completedMessages.has(index)); // Only apply updates if ALL messages have completed their animations if (allMessagesComplete && processingMessages.length > 0) { // Apply pending progress update if (pendingProgressUpdate !== null) { setCurrentProgress(pendingProgressUpdate); setPendingProgressUpdate(null); } // Apply pending completion update only after ALL messages are done if (pendingCompletionData) { setFinalStats(pendingCompletionData.stats); setLoadStatus('success'); onLoadingChange(false); onStatusChange('success'); setCurrentProgress(pendingCompletionData.progress); setPendingCompletionData(null); onProcessingComplete?.(); } } else if (isLastMessageComplete && pendingProgressUpdate !== null && !pendingCompletionData) { // Apply progress updates for non-completion messages immediately after they finish setCurrentProgress(pendingProgressUpdate); setPendingProgressUpdate(null); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [completedMessages, processingMessages.length, pendingProgressUpdate, pendingCompletionData, onLoadingChange, onStatusChange, onProcessingComplete]); // Autoscroll functionality - scroll to bottom when new messages are added useEffect(() => { if (processingMessages.length > 0 && autoScrollEnabled) { // Scroll individual log containers to bottom if (loadingLogRef.current && loadStatus === 'loading') { loadingLogRef.current.scrollTop = loadingLogRef.current.scrollHeight; } if (completeLogRef.current && loadStatus === 'success') { completeLogRef.current.scrollTop = completeLogRef.current.scrollHeight; } if (errorLogRef.current && loadStatus === 'error') { errorLogRef.current.scrollTop = errorLogRef.current.scrollHeight; } // Auto-scroll the main container to bottom to show latest content if (mainContainerRef.current) { mainContainerRef.current.scrollTop = mainContainerRef.current.scrollHeight; } } }, [processingMessages, loadStatus, autoScrollEnabled]); // Helper function to detect if a string is valid JSON const isValidJSON = (str: string): boolean => { try { JSON.parse(str); return true; } catch (e) { return false; } }; // Helper function to format JSON with proper indentation const formatJSON = (jsonString: string, indent: number = 2): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed, null, indent); } catch (e) { return jsonString; } }; // Helper function to minify JSON const minifyJSON = (jsonString: string): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed); } catch (e) { return jsonString; } }; // Helper function to detect if a string is a curl command const isCurlCommand = (str: string): boolean => { return str.trim().startsWith('curl'); }; // Helper function to format curl command with proper indentation const formatCurl = (curlString: string): string => { // Basic curl formatting - split on common flags and add line breaks return curlString .replace(/\s+/g, ' ') // Normalize whitespace .replace(/\s-([a-zA-Z])/g, ' \\\n -$1') // Add line breaks before flags .replace(/\s(https?:\/\/[^\s]+)/g, ' \\\n $1') // Add line breaks before URLs .replace(/\s--([a-zA-Z-]+)/g, ' \\\n --$1') // Add line breaks before long flags .trim(); }; // Helper function to minify curl command const minifyCurl = (curlString: string): string => { return curlString.replace(/\s+/g, ' ').trim(); }; // Helper function to detect if a string is a Display message const isDisplayMessage = (str: string): boolean => { return str.startsWith('Display: '); }; // Helper function to extract filename from Display message const extractFilename = (displayMessage: string): string => { return displayMessage.replace(/^Display:\s*/, '').trim(); }; // Helper function to detect JSON content const detectJsonContent = (text: string): string | null => { try { // Look for JSON-like patterns const jsonMatch = text.match(/\{[\s\S]*\}/); if (jsonMatch) { const potentialJson = jsonMatch[0]; JSON.parse(potentialJson); // Validate it's valid JSON return potentialJson; } } catch (e) { // Not valid JSON } return null; }; // Helper function to detect CURL content const detectCurlContent = (text: string): string | null => { const curlMatch = text.match(/curl\s+[\s\S]*?(?=\n\n|\n"|$)/); return curlMatch ? curlMatch[0] : null; }; // Helper function to format JSON for preview const formatJsonPreview = (jsonString: string): string => { try { const parsed = JSON.parse(jsonString); return JSON.stringify(parsed, null, 2); } catch (e) { return jsonString; } }; // Helper function to format CURL for preview const formatCurlPreview = (curlString: string): string => { return curlString .replace(/\s+--/g, ' \\\n --') .replace(/\s+-([a-zA-Z])/g, ' \\\n -$1') .replace(/\s+(https?:\/\/[^\s]+)/g, ' \\\n $1') .trim(); }; // Ref for the preview container to handle auto-scroll to top const previewContainerRef = useRef(null); // Auto-scroll to top when new preview items are added useEffect(() => { if (previewItems.length > 0 && previewContainerRef.current) { // Scroll to top to show the latest item previewContainerRef.current.scrollTop = 0; } }, [previewItems.length]); // Function to toggle preview item minification const togglePreviewMinification = (id: string) => { setPreviewItems(prev => prev.map(item => item.id === id ? { ...item, isMinified: !item.isMinified } : item ) ); setActivePreviewId(id); }; // Function to handle JSON dialog const handleOpenJsonDialog = (jsonContent: string) => { setSelectedJsonContent(jsonContent); setJsonDialogOpen(true); setIsJsonExpanded(true); }; const handleCloseJsonDialog = () => { setJsonDialogOpen(false); setSelectedJsonContent(''); }; const handleCopyJson = () => { navigator.clipboard.writeText(selectedJsonContent); }; // Function to handle curl dialog const handleOpenCurlDialog = (curlContent: string) => { setSelectedCurlContent(curlContent); setCurlDialogOpen(true); setIsCurlExpanded(true); }; const handleCloseCurlDialog = () => { setCurlDialogOpen(false); setSelectedCurlContent(''); }; const handleCopyCurl = () => { navigator.clipboard.writeText(selectedCurlContent); }; // Function to handle Excel download const handleDownload = async (requestId: string) => { setIsDownloading(true); try { const response = await fetch(`${API_BASE_URI}/${requestId}/download`); if (!response.ok) { throw new Error(`Download failed: ${response.statusText}`); } // Get the filename from the response headers or use a default const contentDisposition = response.headers.get('content-disposition'); let filename = `Benefit_Agent_Report.xlsx`; if (contentDisposition) { const filenameMatch = contentDisposition.match(/filename="?(.+)"?/); if (filenameMatch) { filename = filenameMatch[1]; } } // Convert response to blob and download const blob = await response.blob(); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); // Cleanup document.body.removeChild(link); window.URL.revokeObjectURL(url); } catch (error) { console.error('Download failed:', error); setConnectionError(`Failed to download Excel: ${error instanceof Error ? error.message : 'Unknown error'}`); } finally { setIsDownloading(false); } }; // Function to render message content with typewriting animation const renderMessageContent = (message: string, index: number) => { const isLastMessage = index === processingMessages.length - 1; const shouldAnimate = isLastMessage && loadStatus === 'loading' && !completedMessages.has(index); const handleAnimationComplete = () => { setCompletedMessages(prev => new Set([...Array.from(prev), index])); // After animation completes, check for JSON/CURL content const jsonContent = detectJsonContent(message); if (jsonContent) { addPreviewItem('json', jsonContent); } const curlContent = detectCurlContent(message); if (curlContent) { addPreviewItem('curl', curlContent); } }; // Check if message is a Phase heading const isPhaseHeading = message.startsWith("Phase: "); // Check if message is a Step sub-heading const isStepHeading = message.startsWith("Step: "); // For non-animated messages, check for JSON/CURL content immediately if (!shouldAnimate && !completedMessages.has(index)) { const jsonContent = detectJsonContent(message); if (jsonContent) { addPreviewItem('json', jsonContent); } const curlContent = detectCurlContent(message); if (curlContent) { addPreviewItem('curl', curlContent); } setCompletedMessages(prev => new Set([...Array.from(prev), index])); } if (isValidJSON(message)) { if (shouldAnimate) { return ( handleOpenJsonDialog(message)} /> ); } // Static display for completed messages const preview = message.length > 50 ? message.substring(0, 50) + '...' : message; return ( JSON: {preview} handleOpenJsonDialog(message)} sx={{ color: 'primary.main', '&:hover': { backgroundColor: 'primary.light', color: 'primary.contrastText', } }} > ); } if (isCurlCommand(message)) { if (shouldAnimate) { return ( handleOpenCurlDialog(message)} /> ); } // Static display for completed messages const preview = message.length > 50 ? message.substring(0, 50) + '...' : message; return ( CURL: {preview} handleOpenCurlDialog(message)} sx={{ color: 'warning.main', '&:hover': { backgroundColor: 'warning.light', color: 'warning.contrastText', } }} > ); } if (shouldAnimate) { return ( ); } // Render Phase headings with H1 styling if (isPhaseHeading) { return ( {message.replace(/^Phase:\s*/, '')} ); } // Render Step headings with sub-heading styling if (isStepHeading) { return ( {message.replace(/^Step:\s*/, '')} ); } return ( {message} ); }; // Effect to monitor processing messages and update tooltip state useEffect(() => { if (processingMessages.length === 0) { setProcessingTooltip('Processing'); setIsThinkingMode(false); setIsValidatingMode(false); return; } const latestMessage = processingMessages[processingMessages.length - 1]; const messageText = latestMessage.message.toLowerCase(); // Check for "Quality Assurance and Finalization" heading or status if (messageText.includes('quality assurance and finalization') || messageText.includes('quality assurance') || messageText.includes('finalization')) { setIsValidatingMode(true); setIsThinkingMode(false); setProcessingTooltip('Validating'); return; } // If we're in validating mode, stay in validating mode until completion if (isValidatingMode && !messageText.includes('complete')) { setProcessingTooltip('Validating'); return; } // Check for curl message - switch to "Thinking" if (isCurlCommand(latestMessage.message)) { setIsThinkingMode(true); setIsValidatingMode(false); setProcessingTooltip('Thinking'); return; } // Check for JSON message - revert to "Processing" from "Thinking" if (isThinkingMode && isValidJSON(latestMessage.message)) { setIsThinkingMode(false); setProcessingTooltip('Processing'); return; } // Default state - if not in special modes, show "Processing" if (!isThinkingMode && !isValidatingMode) { setProcessingTooltip('Processing'); } }, [processingMessages, isThinkingMode, isValidatingMode]); const clearData = () => { // Close WebSocket connection if open if (wsRef.current) { wsRef.current.close(); wsRef.current = null; // Clear the reference } // Clear any pending JSON delay timer if (jsonDelayTimer) { clearTimeout(jsonDelayTimer); setJsonDelayTimer(null); } setLoadStatus('idle'); setProcessingMessages([]); setCurrentProgress(0); setFinalStats(null); setConnectionError(null); setIsDownloading(false); setCompletedMessages(new Set()); setCurrentPhase(''); setCurrentStep(''); setPreviewItems([]); setActivePreviewId(null); // Clear processing state setProcessingTooltip('Processing'); setIsThinkingMode(false); setIsValidatingMode(false); // Reset connection state completely setIsConnecting(false); setHasConnected(false); // Reset chat state setHasUserInteracted(false); setIsInputDisabled(false); setUserInput(''); onLoadingChange(false); onStatusChange('idle'); }; // Send chat message handler const handleSendMessage = () => { if (!userInput.trim()) return; // Add user message to the processing log const userMessage: ProcessingMessage = { message: userInput, timestamp: new Date().toLocaleTimeString(), isUser: true }; setProcessingMessages(prev => [...prev, userMessage]); setHasUserInteracted(true); setUserInput(''); setIsInputDisabled(true); // Disable input after sending, re-enable if reset }; // Key press handler for input const handleInputKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSendMessage(); } }; return ( {/* Processing Status Accordion */} setAccordionExpanded(!accordionExpanded)} sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, overflow: 'hidden', '& .MuiAccordionDetails-root': { flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: 0, maxHeight: 'calc(100vh - 220px)' } }} > } sx={{ backgroundColor: 'grey.50', '& .MuiAccordionSummary-content': { alignItems: 'center', }, }} > Processing Status {loadStatus === 'loading' && ( )} {loadStatus === 'success' && ( )} {loadStatus === 'error' && ( )} {/* Auto-scroll toggle button */} { e.stopPropagation(); setAutoScrollEnabled(!autoScrollEnabled); }} sx={{ color: autoScrollEnabled ? 'primary.main' : 'text.secondary', '&:hover': { backgroundColor: autoScrollEnabled ? 'primary.light' : 'grey.200', }, }} > {autoScrollEnabled ? ( ) : ( )} {connectionError && ( {connectionError} )} {loadStatus === 'idle' && ( Configure processing settings and click Load to begin processing. )} {loadStatus === 'loading' && ( {/* Progress Bar */} Processing Progress {currentProgress.toFixed(1)}% {currentPhase && ( Current Phase: {currentPhase} {currentStep && ` - ${currentStep}`} )} {/* Messages Container with Two Columns */} {/* Preview Items Column */} {previewItems.length > 0 && ( Preview Output {previewItems.map((item) => ( togglePreviewMinification(item.id)} > {item.timestamp} {item.type === 'pdf' ? ( {item.filename} {item.isMinified ? ( Click to view PDF ) : ( item.pdfUrl && ( ) )} ) : ( {item.isMinified ? (item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content) : (item.type === 'json' ? formatJsonPreview(item.content) : formatCurlPreview(item.content)) } {!item.isMinified && ( { e.stopPropagation(); navigator.clipboard.writeText(item.content); }} > { e.stopPropagation(); if (item.type === 'json') { handleOpenJsonDialog(item.content); } else { handleOpenCurlDialog(item.content); } }} > )} )} ))} )} {/* Processing Messages Column - Chat Interface */} Chat Assistant {!hasUserInteracted && ( Hello! I'm your Benefit Agent Assistant. Type a message below to start processing your request. )} {processingMessages.map((msg, index) => ( {!msg.isUser && ( )} {/* If it is a user message, just render text, otherwise use the complex renderer */} {msg.isUser ? ( {msg.message} ) : ( renderMessageContent(msg.message, index) )} {msg.timestamp} {msg.isUser && ( )} ))} {/* Input Area */} setUserInput(e.target.value)} onKeyDown={handleInputKeyPress} disabled={hasUserInteracted && isInputDisabled} size="small" variant="outlined" sx={{ backgroundColor: 'white' }} InputProps={{ endAdornment: ( ), }} /> )} {loadStatus === 'success' && ( {/* Success Status Card */} Processing Complete {finalStats && ( Status: {finalStats.status} Records Processed: {finalStats.number_of_records} Request ID: {finalStats.request_id} {/* Download Button */} )} {/* Completed Messages Log */} Conversation History {processingMessages.map((msg, index) => ( {!msg.isUser && ( )} {msg.isUser ? ( {msg.message} ) : ( renderMessageContent(msg.message, index) )} {msg.timestamp} {msg.isUser && ( )} ))} )} {loadStatus === 'error' && ( {/* Error Status Card */} Processing Failed {/* Error Messages Log */} {processingMessages.length > 0 && ( Conversation History {processingMessages.map((msg, index) => ( {!msg.isUser && ( )} {msg.isUser ? ( {msg.message} ) : ( renderMessageContent(msg.message, index) )} {msg.timestamp} {msg.isUser && ( )} ))} )} )} {/* JSON Dialog */} JSON Content setIsJsonExpanded(!isJsonExpanded)} size="small" sx={{ mr: 1 }} > {isJsonExpanded ? : } {/* CURL Dialog */} CURL Command setIsCurlExpanded(!isCurlExpanded)} size="small" sx={{ mr: 1 }} > {isCurlExpanded ? : } ); }; export default ProcessingStatus;