import React, { useState, useRef, useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { PaperAirplaneIcon, StopIcon } from '@heroicons/react/24/solid'; import MessageBubble from './MessageBubble'; import TypingIndicator from './TypingIndicator'; import FileUploader from './FileUploader'; import { sendMessage, sendMessageStream } from '../services/api'; import toast from 'react-hot-toast'; const ChatInterface = ({ conversationId, conversations, setConversations, darkMode }) => { const [message, setMessage] = useState(''); const [isLoading, setIsLoading] = useState(false); const [showFileUploader, setShowFileUploader] = useState(false); const messagesEndRef = useRef(null); const textareaRef = useRef(null); const currentConversation = conversations.find(conv => conv.id === conversationId); const messages = currentConversation?.messages || []; const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [messages]); const handleSubmit = async (e) => { e.preventDefault(); if (!message.trim() || isLoading) return; const userMessage = { id: Date.now().toString(), role: 'user', content: message.trim(), timestamp: new Date(), }; // Add user message immediately setConversations(prev => prev.map(conv => conv.id === conversationId ? { ...conv, messages: [...conv.messages, userMessage], title: conv.messages.length === 0 ? message.slice(0, 50) + '...' : conv.title } : conv )); setMessage(''); setIsLoading(true); const assistantMessageId = (Date.now() + 1).toString(); try { let fullResponse = ''; // Add a placeholder for the assistant's message setConversations(prev => prev.map(conv => conv.id === conversationId ? { ...conv, messages: [...conv.messages, { id: assistantMessageId, role: 'assistant', content: '', timestamp: new Date() }] } : conv )); await sendMessageStream(message.trim(), (chunk) => { fullResponse += chunk; setConversations(prev => prev.map(conv => conv.id === conversationId ? { ...conv, messages: conv.messages.map(msg => msg.id === assistantMessageId ? { ...msg, content: fullResponse } : msg ), } : conv )); }); } catch (error) { toast.error('Failed to send message. Please try again.'); console.error('Error sending message:', error); // Optional: remove placeholder on error setConversations(prev => prev.map(conv => conv.id === conversationId ? { ...conv, messages: conv.messages.filter(msg => msg.id !== assistantMessageId) } : conv )); } finally { setIsLoading(false); } }; const handleKeyDown = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(e); } }; const adjustTextareaHeight = () => { const textarea = textareaRef.current; if (textarea) { textarea.style.height = 'auto'; textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'; } }; useEffect(() => { adjustTextareaHeight(); }, [message]); return (
{/* Messages Container */}
{/* Empty State */} {messages.length === 0 && !isLoading && ( {/* CA Assistant Avatar */} {/* Welcome Message */} Hello! I'm your CA Study Assistant I'm here to help you with accounting, finance, taxation, and auditing concepts. Ask me anything or upload your study materials! {/* Quick Start Suggestions */}

Try asking me about:

{[ { icon: "📊", text: "Financial statement analysis", query: "Explain financial statement analysis" }, { icon: "💰", text: "Depreciation methods", query: "What are different depreciation methods?" }, { icon: "🏦", text: "Working capital management", query: "Explain working capital management" }, { icon: "📈", text: "Ratio analysis", query: "How to perform ratio analysis?" }, { icon: "📋", text: "Auditing procedures", query: "What are key auditing procedures?" }, { icon: "💼", text: "Tax planning strategies", query: "Explain tax planning strategies" } ].map((suggestion, index) => ( setMessage(suggestion.query)} className={`flex items-center p-4 rounded-xl text-left transition-all ${ darkMode ? 'bg-gray-800 hover:bg-gray-700 border-gray-700 text-gray-300' : 'bg-gray-50 hover:bg-gray-100 border-gray-200 text-gray-700' } border hover:border-primary-300 hover:shadow-md`} > {suggestion.icon} {suggestion.text} ))}
{/* Upload Reminder */}
💡 Upload your study materials for more specific and detailed answers
)} {/* Messages */} {messages.map((msg, index) => ( ))} {isLoading && }
{/* File Uploader Modal */} {showFileUploader && ( setShowFileUploader(false)} > e.stopPropagation()} className={`max-w-md w-full p-6 rounded-2xl ${ darkMode ? 'bg-gray-800' : 'bg-white' } shadow-2xl`} >

Upload Document

setShowFileUploader(false)} />
)}
{/* Input Area */}
{/* Enhanced Input Container */}
{/* Subtle Inner Glow */}
{/* Input Content */}
{/* File Upload Button */} setShowFileUploader(true)} className={`flex-shrink-0 p-3 rounded-xl transition-all duration-200 ${ darkMode ? 'hover:bg-gray-700/70 text-gray-400 hover:text-primary-400 hover:shadow-lg' : 'hover:bg-gray-100/70 text-gray-500 hover:text-primary-600 hover:shadow-md' } relative group backdrop-blur-sm`} title="Upload document" > {/* Enhanced Tooltip */}
Upload documents
{/* Enhanced Text Input */}