NeahStable/components/parole.tsx
2026-01-16 00:12:15 +01:00

280 lines
10 KiB
TypeScript

"use client";
import { useEffect, useState, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, MessageSquare, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { signIn, useSession } from "next-auth/react";
import { useWidgetNotification } from "@/hooks/use-widget-notification";
import { useUnifiedRefresh } from "@/hooks/use-unified-refresh";
import { REFRESH_INTERVALS } from "@/lib/constants/refresh-intervals";
import { Badge } from "@/components/ui/badge";
interface Message {
id: string;
text: string;
timestamp: string;
rawTimestamp: string;
roomName: string;
roomType: string;
sender: {
_id: string;
username: string;
name: string;
initials: string;
color: string;
};
isOwnMessage: boolean;
room: {
id: string;
type: string;
name: string;
isChannel: boolean;
isPrivateGroup: boolean;
isDirect: boolean;
link: string;
};
}
export function Parole() {
const [messages, setMessages] = useState<Message[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [unreadCount, setUnreadCount] = useState<number>(0);
const router = useRouter();
const { data: session, status } = useSession();
const { triggerNotification } = useWidgetNotification();
const lastUnreadCountRef = useRef<number>(-1); // Initialize to -1 to detect first load
const isInitializedRef = useRef<boolean>(false);
const fetchMessages = async (forceRefresh = false) => {
// Only show loading spinner on initial load, not on auto-refresh
if (!messages.length) {
setLoading(true);
}
setRefreshing(true);
setError(null);
try {
const response = await fetch('/api/rocket-chat/messages' + (forceRefresh ? '?refresh=true' : ''), {
cache: 'no-store',
next: { revalidate: 0 },
credentials: 'include',
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch messages');
}
const data = await response.json();
if (Array.isArray(data.messages)) {
// Utiliser le totalUnreadCount de l'API (plus fiable)
const currentUnreadCount = data.totalUnreadCount || 0;
// Update unread count state for badge display
setUnreadCount(currentUnreadCount);
// On initialise le count au premier chargement
if (!isInitializedRef.current) {
isInitializedRef.current = true;
lastUnreadCountRef.current = -1; // Set to -1 to trigger on first load
console.log('[Parole] Initial unread count:', currentUnreadCount);
}
// Si le count a changé (ou premier chargement), déclencher notification
if (currentUnreadCount !== lastUnreadCountRef.current) {
lastUnreadCountRef.current = currentUnreadCount;
// Préparer les items pour les notifications (messages, max 10)
const notificationItems = data.messages
.slice(0, 10)
.map((msg: any) => ({
id: msg.id,
title: msg.sender.name || msg.sender.username,
message: msg.text || msg.message || '',
link: '/parole',
timestamp: new Date(msg.rawTimestamp || msg.timestamp),
metadata: {
roomName: msg.roomName,
roomType: msg.roomType,
},
}));
// Déclencher notification update
await triggerNotification({
source: 'rocketchat',
count: currentUnreadCount,
items: notificationItems,
});
}
setMessages(data.messages);
} else {
console.warn('Unexpected data format:', data);
setMessages([]);
}
setError(null);
} catch (err) {
console.error('Error fetching messages:', err);
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages';
setError(errorMessage);
} finally {
setLoading(false);
setRefreshing(false);
}
};
// Initial fetch on mount
useEffect(() => {
if (status === 'authenticated') {
fetchMessages(false); // Use cache on initial load
}
}, [status]);
// Integrate unified refresh for automatic polling
const { refresh } = useUnifiedRefresh({
resource: 'parole',
interval: REFRESH_INTERVALS.PAROLE, // 30 seconds
enabled: status === 'authenticated',
onRefresh: async () => {
await fetchMessages(false); // Use cache for auto-refresh
},
priority: 'high',
});
// Manual refresh handler (bypasses cache)
const handleManualRefresh = async (e?: React.MouseEvent) => {
if (e) {
e.stopPropagation();
}
await fetchMessages(true); // Force refresh, bypass cache
};
if (status === 'loading') {
return (
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
<CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
<CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
<MessageSquare className="h-5 w-5 text-gray-600" />
Parole
</CardTitle>
</CardHeader>
<CardContent className="p-6">
<p className="text-center text-gray-500">Loading...</p>
</CardContent>
</Card>
);
}
if (status === 'unauthenticated' || (error && error.includes('Session expired'))) {
return (
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
<CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
<CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
<MessageSquare className="h-5 w-5 text-gray-600" />
Parole
</CardTitle>
</CardHeader>
<CardContent className="p-6">
<div className="text-center">
<p className="text-gray-500 mb-4">Please sign in to view messages</p>
<Button
onClick={(e) => {
e.stopPropagation();
signIn('keycloak');
}}
variant="default"
className="bg-blue-600 hover:bg-blue-700 text-white"
>
Sign In
</Button>
</div>
</CardContent>
</Card>
);
}
return (
<Card
className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg cursor-pointer w-full"
onClick={() => router.push('/parole')}
>
<CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
<CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
<MessageSquare className="h-5 w-5 text-gray-600" />
Parole
{unreadCount > 0 && (
<Badge variant="destructive" className="ml-1 text-xs">
{unreadCount}
</Badge>
)}
</CardTitle>
<Button
variant="ghost"
size="icon"
onClick={handleManualRefresh}
disabled={refreshing}
className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
>
<RefreshCw className={`h-3.5 w-3.5 text-gray-600 ${refreshing ? 'animate-spin' : ''}`} />
</Button>
</CardHeader>
<CardContent className="p-4">
{loading && messages.length === 0 ? (
<div className="text-center py-6 flex flex-col items-center">
<Loader2 className="h-6 w-6 animate-spin text-gray-400 mb-2" />
<p className="text-gray-500">Chargement des messages...</p>
</div>
) : error ? (
<div className="text-center py-4">
<p className="text-red-500 text-sm mb-2">{error}</p>
<Button
variant="outline"
onClick={handleManualRefresh}
className="mt-2"
>
Réessayer
</Button>
</div>
) : (
<div className="space-y-4 max-h-[400px] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
{messages.length === 0 ? (
<p className="text-center text-gray-500 py-6">Aucun message</p>
) : (
messages.map((message) => (
<div key={message.id} className="flex items-start space-x-3 hover:bg-gray-50/50 p-3 rounded-lg transition-colors">
<Avatar className="h-8 w-8" style={{ backgroundColor: message.sender.color }}>
<AvatarImage src={`https://ui-avatars.com/api/?name=${encodeURIComponent(message.sender.name)}&background=random`} />
<AvatarFallback>{message.sender.initials}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-baseline justify-between space-x-2">
<p className="text-sm font-semibold text-gray-800 truncate max-w-[70%]">{message.sender.name}</p>
<span className="text-xs font-medium text-gray-500 flex-shrink-0">{message.timestamp}</span>
</div>
<p className="text-sm text-gray-600 whitespace-pre-wrap line-clamp-2 mt-1">{message.text}</p>
{message.roomName && (
<div className="flex items-center mt-2">
<span className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${
message.room.isChannel ? 'bg-blue-50 text-blue-700' :
message.room.isPrivateGroup ? 'bg-purple-50 text-purple-700' :
'bg-green-50 text-green-700'
}`}>
{message.room.isChannel ? '#' : message.room.isPrivateGroup ? '🔒' : '💬'} {message.roomName}
</span>
</div>
)}
</div>
</div>
))
)}
</div>
)}
</CardContent>
</Card>
);
}