nagur-shareef-shaik's picture
Upload 5 files (#3)
66f3298 verified
raw
history blame
3.23 kB
import { useState, useEffect, useRef } from 'react';
import { ApiResponse, ChatMessage, UserProfile } from '../../interface';
import { CHAT_ENDPOINT } from '../../endpoint';
export function useChatInterface(userProfile: UserProfile, isProfileComplete?: boolean) {
const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [currentMessage, setCurrentMessage] = useState('');
const [showPlanRecs, setShowPlanRecs] = useState<boolean>(false);
const chatEndRef = useRef<HTMLDivElement>(null);
// threadId is generated once per chat session and persists for the hook's lifetime
const [threadId] = useState(() => crypto.randomUUID());
useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [chatHistory]);
const sendChatMessage = async (
message: string,
profileOverride?: UserProfile
) => {
setIsLoading(true);
try {
const payload = {
thread_id: threadId,
user_profile: profileOverride ?? userProfile,
message,
is_profile_complete: isProfileComplete ?? false,
conversation_history: chatHistory.map(m => `${m.role}: ${m.content}`)
};
const response = await fetch(CHAT_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) throw new Error('Failed to send message');
const data: ApiResponse = await response.json();
// Update state from backend response
// let newHistory: ChatMessage[] = data.updated_history.map(msg => {
// const [role, ...contentParts] = msg.split(':');
// return {
// role: role.toLowerCase() as 'user' | 'agent',
// content: contentParts.join(':').trim(),
// timestamp: Date.now()
// };
// });
let newHistory: ChatMessage[] = [...chatHistory, {
role: 'agent',
content: data.updated_history[data.updated_history.length - 1],
timestamp: Date.now(),
plans: !showPlanRecs && data.plan_recommendations?.recommendations?.length && data.plan_recommendations?.recommendations?.length > 0 ? data.plan_recommendations.recommendations : undefined
}];
setChatHistory(newHistory);
if (!showPlanRecs && data.plan_recommendations?.recommendations?.length && data.plan_recommendations?.recommendations?.length > 0) {
setShowPlanRecs(true);
}
return data;
} catch (error) {
console.error('Error sending message:', error);
} finally {
setIsLoading(false);
}
};
const handleSendMessage = async () => {
if (!currentMessage.trim()) return;
// Add user message to chat immediately
const userMessage: ChatMessage = {
role: 'user',
content: currentMessage,
timestamp: Date.now()
};
setChatHistory(prev => [...prev, userMessage]);
const messageToSend = currentMessage;
setCurrentMessage('');
await sendChatMessage(messageToSend);
};
return {
chatHistory,
isLoading,
currentMessage,
setCurrentMessage,
handleSendMessage,
showPlanRecs,
chatEndRef,
sendChatMessage
};
}