|
| 1 | +import React, { useState } from 'react'; |
| 2 | + |
| 3 | +import { sendChatMessage } from '@/services/collab-service'; |
| 4 | + |
| 5 | +import { ChatLayout } from './chat/chat-layout'; |
| 6 | +import { ChatMessageType } from './chat/chat-message'; |
| 7 | + |
| 8 | +// Types for OpenAI API |
| 9 | +// interface OpenAIMessage { |
| 10 | +// role: 'user' | 'assistant'; |
| 11 | +// content: string; |
| 12 | +// } |
| 13 | + |
| 14 | +interface AIChatProps { |
| 15 | + isOpen: boolean; |
| 16 | + onClose: () => void; |
| 17 | +} |
| 18 | + |
| 19 | +// const API_URL = 'https://api.openai.com/v1/chat/completions'; |
| 20 | +// const API_KEY = process.env.OPENAI_API_KEY; |
| 21 | + |
| 22 | +export const AIChat: React.FC<AIChatProps> = ({ isOpen, onClose }) => { |
| 23 | + const [messages, setMessages] = useState<ChatMessageType[]>([]); |
| 24 | + const [isLoading, setIsLoading] = useState<boolean>(false); |
| 25 | + const [error, setError] = useState<string | null>(null); |
| 26 | + |
| 27 | + const handleSend = async (userMessage: string): Promise<void> => { |
| 28 | + if (!userMessage.trim() || isLoading) return; |
| 29 | + |
| 30 | + const updatedMessages = [ |
| 31 | + ...messages, |
| 32 | + { text: userMessage, isUser: true, timestamp: new Date() }, |
| 33 | + ]; |
| 34 | + |
| 35 | + setMessages(updatedMessages); |
| 36 | + setIsLoading(true); |
| 37 | + setError(null); |
| 38 | + |
| 39 | + const inputMessages = updatedMessages.map((message) => ({ |
| 40 | + role: message.isUser ? 'user' : 'assistant', |
| 41 | + content: message.text, |
| 42 | + })); |
| 43 | + |
| 44 | + try { |
| 45 | + const response = await sendChatMessage(inputMessages); |
| 46 | + setMessages((prev) => [ |
| 47 | + ...prev, |
| 48 | + { text: response?.message, isUser: false, timestamp: new Date() }, |
| 49 | + ]); |
| 50 | + } catch (err) { |
| 51 | + setError( |
| 52 | + err instanceof Error ? err.message : 'An error occurred while fetching the response' |
| 53 | + ); |
| 54 | + } finally { |
| 55 | + setIsLoading(false); |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + return ( |
| 60 | + <ChatLayout |
| 61 | + isOpen={isOpen} |
| 62 | + onClose={onClose} |
| 63 | + messages={messages} |
| 64 | + onSend={handleSend} |
| 65 | + isLoading={isLoading} |
| 66 | + error={error} |
| 67 | + title='AI Assistant' |
| 68 | + /> |
| 69 | + ); |
| 70 | +}; |
0 commit comments