'use client'; import { useState, useEffect } from 'react'; import useSWR from 'swr'; import AlertModal from './AlertModal'; import ConfirmModal from './ConfirmModal'; interface User { id: string; email: string; name: string | null; } interface Participant { id: string; email: string; name: string | null; } interface Conversation { id: string; name: string | null; type: string; displayName: string; participants: Participant[]; } interface GroupSettingsModalProps { conversation: Conversation; onClose: () => void; onUpdate: () => void; } const fetcher = (url: string) => fetch(url).then((res) => res.json()); export default function GroupSettingsModal({ conversation, onClose, onUpdate, }: GroupSettingsModalProps) { const [groupName, setGroupName] = useState(conversation.name || ''); const [search, setSearch] = useState(''); const [selectedUsers, setSelectedUsers] = useState([]); const [isUpdating, setIsUpdating] = useState(false); const [isAdding, setIsAdding] = useState(false); const [alertModal, setAlertModal] = useState<{ show: boolean; type: 'success' | 'error' | 'info' | 'warning'; title: string; message: string; } | null>(null); const [confirmModal, setConfirmModal] = useState<{ show: boolean; userId: string | null; } | null>(null); const { data: users, error } = useSWR( search ? `/api/users?search=${encodeURIComponent(search)}` : null, fetcher ); const existingParticipantIds = conversation.participants.map((p) => p.id); const handleUpdateName = async () => { if (!groupName.trim()) { setAlertModal({ show: true, type: 'warning', title: 'Nom requis', message: 'Le nom du groupe ne peut pas être vide', }); return; } setIsUpdating(true); try { const response = await fetch(`/api/conversations/${conversation.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: groupName }), }); if (response.ok) { onUpdate(); onClose(); } else { const error = await response.json(); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: error.error || 'Erreur lors de la mise à jour', }); } } catch (error) { console.error('Erreur:', error); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: 'Erreur lors de la mise à jour', }); } finally { setIsUpdating(false); } }; const handleAddParticipants = async () => { if (selectedUsers.length === 0) { setAlertModal({ show: true, type: 'warning', title: 'Sélection requise', message: 'Veuillez sélectionner au moins un utilisateur', }); return; } setIsAdding(true); try { const response = await fetch(`/api/conversations/${conversation.id}/participants`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ userIds: selectedUsers }), }); if (response.ok) { setSelectedUsers([]); setSearch(''); onUpdate(); } else { const error = await response.json(); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: error.error || 'Erreur lors de l\'ajout des participants', }); } } catch (error) { console.error('Erreur:', error); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: 'Erreur lors de l\'ajout des participants', }); } finally { setIsAdding(false); } }; const handleRemoveParticipant = async (userId: string) => { setConfirmModal({ show: true, userId, }); }; const confirmRemoveParticipant = async () => { if (!confirmModal?.userId) return; try { const response = await fetch( `/api/conversations/${conversation.id}/participants?userId=${confirmModal.userId}`, { method: 'DELETE', } ); if (response.ok) { onUpdate(); setConfirmModal(null); } else { const error = await response.json(); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: error.error || 'Erreur lors du retrait du participant', }); setConfirmModal(null); } } catch (error) { console.error('Erreur:', error); setAlertModal({ show: true, type: 'error', title: 'Erreur', message: 'Erreur lors du retrait du participant', }); setConfirmModal(null); } }; const handleUserToggle = (userId: string) => { if (selectedUsers.includes(userId)) { setSelectedUsers(selectedUsers.filter((id) => id !== userId)); } else { setSelectedUsers([...selectedUsers, userId]); } }; const availableUsers = users?.filter((u) => !existingParticipantIds.includes(u.id)) || []; return (

Paramètres du groupe

{/* Nom du groupe */}
setGroupName(e.target.value)} className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent" />
{/* Participants existants */}

Participants ({conversation.participants.length})

{conversation.participants.map((participant) => (
{participant.name || 'Utilisateur'}
{participant.email}
))}
{/* Ajouter des participants */}

Ajouter des participants

setSearch(e.target.value)} placeholder="Rechercher des utilisateurs..." className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-lblue focus:border-transparent" /> {search && ( <> {error && (
Erreur lors de la recherche
)} {!users && !error && (
Recherche...
)} {availableUsers.length === 0 && users && (
Aucun utilisateur disponible ou déjà dans le groupe
)} {availableUsers.length > 0 && ( <>
{availableUsers.map((user) => ( ))}
{selectedUsers.length > 0 && ( )} )} )}
{/* Modal d'alerte */} {alertModal && ( setAlertModal(null)} /> )} {/* Modal de confirmation */} {confirmModal && ( setConfirmModal(null)} /> )}
); }