'use client'; import { useState, useEffect } from 'react'; import useSWR from 'swr'; import ChatWindow from './ChatWindow'; import NewConversationModal from './NewConversationModal'; import GroupSettingsModal from './GroupSettingsModal'; interface User { id: string; email: string; name: string | null; } interface Participant { id: string; email: string; name: string | null; } interface LastMessage { id: string; content: string | null; senderId: string; senderName: string; createdAt: string; hasFiles: boolean; } interface Conversation { id: string; name: string | null; type: string; displayName: string; participants: Participant[]; lastMessage: LastMessage | null; unreadCount: number; updatedAt: string; createdAt: string; } const fetcher = (url: string) => fetch(url).then((res) => res.json()); export default function Messagerie() { const [selectedConversation, setSelectedConversation] = useState(null); const [showNewConversation, setShowNewConversation] = useState(false); const [showGroupSettings, setShowGroupSettings] = useState(false); const { data: conversations, error, mutate } = useSWR( '/api/conversations', fetcher, { refreshInterval: 2000, // Rafraîchir toutes les 2 secondes } ); const selectedConv = conversations?.find((c) => c.id === selectedConversation); useEffect(() => { // Sélectionner automatiquement la première conversation si aucune n'est sélectionnée if (!selectedConversation && conversations && conversations.length > 0) { setSelectedConversation(conversations[0].id); } }, [conversations, selectedConversation]); const handleNewMessage = () => { // Rafraîchir la liste des conversations quand un nouveau message arrive mutate(); }; return (
{/* Liste des conversations */}

Messages

{error && (
Erreur lors du chargement des conversations
)} {!conversations && !error && (
Chargement...
)} {conversations && conversations.length === 0 && (
Aucune conversation. Créez-en une nouvelle !
)} {conversations && conversations.length > 0 && (
{conversations.map((conversation) => ( ))}
)}
{/* Fenêtre de chat */}
{selectedConversation && selectedConv ? ( setShowGroupSettings(true)} /> ) : (

Sélectionnez une conversation pour commencer

)}
{/* Modales */} {showNewConversation && ( setShowNewConversation(false)} onConversationCreated={(conversationId) => { setSelectedConversation(conversationId); setShowNewConversation(false); mutate(); }} /> )} {showGroupSettings && selectedConv && selectedConv.type === 'group' && ( setShowGroupSettings(false)} onUpdate={mutate} /> )}
); }