([])
const [input, setInput] = useState('')
const [isLoading, setIsLoading] = useState(false)
const messagesEndRef = useRef'use client'
import { useState, useRef, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { useToast } from "@/components/ui/use-toast"
type Message = {
role: 'user' | 'assistant'
content: string
}
export default function ChatInterface() {
const [messages, setMessages] = useState<Message[]>([])
const [input, setInput] = useState('')
const [isLoading, setIsLoading] = useState(false)
const messagesEndRef = useRef<HTMLDivElement>(null)
const { toast } = useToast()
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
}
useEffect(scrollToBottom, [messages])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!input.trim()) return
const userMessage: Message = { role: 'user', content: input }
setMessages(prev => [...prev, userMessage])
setInput('')
setIsLoading(true)
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: input }),
})
if (!response.ok) {
throw new Error('Failed to get response')
}
const data = await response.json()
const aiMessage: Message = {
role: 'assistant',
content: data.result
}
setMessages(prev => [...prev, aiMessage])
} catch (err: unknown) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get response from AI'
toast({
title: "Error",
description: errorMessage,
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}
return (
<Card className="w-full max-w-4xl mx-auto">
<CardContent className="p-6">
<ScrollArea className="h-[60vh] w-full pr-4">
{messages.map((message, index) => (
<div
key={index}
className={`mb-4 ${
message.role === 'user' ? 'text-right' : 'text-left'
}`}
>
<span
className={`inline-block p-2 rounded-lg ${
message.role === 'user'
? 'bg-primary text-primary-foreground'
: 'bg-muted'
}`}
>
{message.content}
</span>
</div>
))}
<div ref={messagesEndRef} />
</ScrollArea>
<form onSubmit={handleSubmit} className="flex items-center space-x-2">
<Input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
disabled={isLoading}
/>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Sending...' : 'Send'}
</Button>
</form>
</CardContent>
</Card>
)
}