import { useState, useCallback } from 'react'; import { api } from '@/services/api'; export interface ChatMessage { id: string; role: 'user' | 'assistant'; content: string; type?: 'message' | 'scan_started' | 'transactions' | 'stats' | 'scan_history' | 'search_results' | 'error'; data?: any; timestamp: Date; } const WELCOME_MESSAGE: ChatMessage = { id: 'welcome', role: 'assistant', content: "Bonjour! Je suis l'assistant ICC. Je peux scanner vos courriels, afficher les transactions, ou consulter les statistiques. Comment puis-je vous aider?", type: 'message', timestamp: new Date(), }; export function useChatAssistant() { const [messages, setMessages] = useState([WELCOME_MESSAGE]); const [isLoading, setIsLoading] = useState(false); const sendMessage = useCallback(async (text: string) => { const userMsg: ChatMessage = { id: `user_${Date.now()}`, role: 'user', content: text, timestamp: new Date(), }; setMessages((prev) => [...prev, userMsg]); setIsLoading(true); try { const response = await api.post<{ type: string; message: string; data?: any; }>('/chat/message', { message: text }); const assistantMsg: ChatMessage = { id: `assistant_${Date.now()}`, role: 'assistant', content: response.message, type: response.type as ChatMessage['type'], data: response.data, timestamp: new Date(), }; setMessages((prev) => [...prev, assistantMsg]); } catch (error: any) { const errorMsg: ChatMessage = { id: `error_${Date.now()}`, role: 'assistant', content: error.message || 'Une erreur est survenue. Réessayez.', type: 'error', timestamp: new Date(), }; setMessages((prev) => [...prev, errorMsg]); } finally { setIsLoading(false); } }, []); const clearHistory = useCallback(() => { setMessages([WELCOME_MESSAGE]); }, []); return { messages, isLoading, sendMessage, clearHistory }; }