import { useState, useRef, useEffect } from 'react' import { Send, Loader2, MessageCircle } from 'lucide-react' import ReactMarkdown from 'react-markdown' import rehypeHighlight from 'rehype-highlight' export default function ChatInterface() { const [messages, setMessages] = useState([ { id: 1, role: 'assistant', content: "Hello! I'm your AI assistant. I can help you with questions, have conversations, provide explanations, and assist with various topics. What would you like to talk about?", timestamp: new Date().toISOString() } ]) const [inputMessage, setInputMessage] = useState('') const [isLoading, setIsLoading] = useState(false) const messagesEndRef = useRef(null) const inputRef = useRef(null) const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) } useEffect(() => { scrollToBottom() }, [messages]) const handleSubmit = async (e) => { e.preventDefault() if (!inputMessage.trim() || isLoading) return const userMessage = { id: Date.now(), role: 'user', content: inputMessage.trim(), timestamp: new Date().toISOString() } setMessages(prev => [...prev, userMessage]) setInputMessage('') setIsLoading(true) try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userMessage.content, messages: messages.filter(m => m.role !== 'system') }), }) if (!response.ok) { throw new Error('Failed to get response') } const data = await response.json() const assistantMessage = { id: Date.now() + 1, role: 'assistant', content: data.message, timestamp: data.timestamp || new Date().toISOString() } setMessages(prev => [...prev, assistantMessage]) } catch (error) { console.error('Chat error:', error) const errorMessage = { id: Date.now() + 1, role: 'assistant', content: "I apologize, but I'm having trouble connecting right now. Please try again in a moment.", timestamp: new Date().toISOString() } setMessages(prev => [...prev, errorMessage]) } finally { setIsLoading(false) inputRef.current?.focus() } } const handleKeyPress = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleSubmit(e) } } const formatTime = (timestamp) => { return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) } return (
Start a conversation with the AI assistant
{children}
, code: ({ children, className }) => { const isInline = !className return isInline ? (
{children}
) : (
{children}
)
}
>
{message.content}