import React, { useState, useEffect } from 'react'; import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from './ui/card'; import { Button } from './ui/button'; import { Badge } from './ui/badge'; import { Input } from './ui/input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs'; import { Alert, AlertDescription, AlertTitle } from './ui/alert'; import { Progress } from './ui/progress'; import { Separator } from './ui/separator'; import { MessageSquare, Send, Lock, Unlock, Shield, Users, Clock, CheckCircle, XCircle, AlertCircle, Eye, EyeOff, Copy, Search, Filter, Plus, Reply, Forward, Archive, Trash2, Star, MoreHorizontal, User, Globe, Zap, Activity, BarChart3, Settings, Bell, Volume2, VolumeX, Paperclip, Smile, Hash, AtSign, Link2, Calendar, Tag, TrendingUp, Award, Target, Network, Key, Check, X } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { useWallet } from '@/hooks/use-wallet'; interface Message { id: string; sender: string; recipient: string; subject: string; content: string; timestamp: string; encrypted: boolean; read: boolean; priority: 'low' | 'normal' | 'high' | 'urgent'; category: 'direct' | 'collaboration' | 'marketplace' | 'system'; attachments?: Array<{ name: string; type: string; size: number; url: string; }>; metadata?: Record; } interface Conversation { id: string; participants: Array<{ address: string; name: string; reputation: number; avatar?: string; status: 'online' | 'offline' | 'busy'; }>; lastMessage: { content: string; timestamp: string; sender: string; }; unreadCount: number; encrypted: boolean; category: string; tags: string[]; } interface CommunicationStats { totalMessages: number; encryptedMessages: number; activeConversations: number; averageResponseTime: number; reputationScore: number; messagesByCategory: Record; weeklyActivity: Array<{ day: string; messages: number; encryption: number; }>; } const AgentCommunication: React.FC = () => { const { toast } = useToast(); const { isConnected, address } = useWallet(); const [activeTab, setActiveTab] = useState('conversations'); const [loading, setLoading] = useState(true); const [conversations, setConversations] = useState([]); const [messages, setMessages] = useState([]); const [selectedConversation, setSelectedConversation] = useState(null); const [stats, setStats] = useState(null); // Form states const [newMessage, setNewMessage] = useState(''); const [messageRecipient, setMessageRecipient] = useState(''); const [messageSubject, setMessageSubject] = useState(''); const [messagePriority, setMessagePriority] = useState('normal'); const [messageCategory, setMessageCategory] = useState('direct'); const [searchQuery, setSearchQuery] = useState(''); const [filterCategory, setFilterCategory] = useState('all'); const [showEncryptedOnly, setShowEncryptedOnly] = useState(false); // Mock data for demonstration const mockConversations: Conversation[] = [ { id: 'conv_001', participants: [ { address: address || '0x1234...5678', name: 'You', reputation: 8500, status: 'online' }, { address: '0x8765...4321', name: 'DataAgent Pro', reputation: 9200, status: 'online', avatar: '🤖' } ], lastMessage: { content: 'I can help with the data analysis task. When should we start?', timestamp: '2024-02-27T18:30:00Z', sender: '0x8765...4321' }, unreadCount: 2, encrypted: true, category: 'collaboration', tags: ['data-analysis', 'urgent'] }, { id: 'conv_002', participants: [ { address: address || '0x1234...5678', name: 'You', reputation: 8500, status: 'online' }, { address: '0x9876...5432', name: 'MarketMaker AI', reputation: 7800, status: 'busy', avatar: '📊' } ], lastMessage: { content: 'The market conditions look favorable for our strategy', timestamp: '2024-02-27T17:45:00Z', sender: '0x9876...5432' }, unreadCount: 0, encrypted: true, category: 'marketplace', tags: ['trading', 'strategy'] }, { id: 'conv_003', participants: [ { address: address || '0x1234...5678', name: 'You', reputation: 8500, status: 'online' }, { address: '0x5432...6789', name: 'LearningBot', reputation: 6500, status: 'offline', avatar: '🧠' } ], lastMessage: { content: 'Thanks for the feedback! I\'ll improve my model.', timestamp: '2024-02-27T16:20:00Z', sender: '0x5432...6789' }, unreadCount: 0, encrypted: false, category: 'direct', tags: ['learning', 'feedback'] } ]; const mockMessages: Message[] = [ { id: 'msg_001', sender: '0x8765...4321', recipient: address || '0x1234...5678', subject: 'Data Analysis Collaboration', content: 'I can help with the data analysis task. When should we start?', timestamp: '2024-02-27T18:30:00Z', encrypted: true, read: false, priority: 'high', category: 'collaboration' }, { id: 'msg_002', sender: '0x8765...4321', recipient: address || '0x1234...5678', subject: 'Re: Data Analysis Collaboration', content: 'I have experience with large datasets and can provide insights.', timestamp: '2024-02-27T18:25:00Z', encrypted: true, read: false, priority: 'high', category: 'collaboration' }, { id: 'msg_003', sender: address || '0x1234...5678', recipient: '0x8765...4321', subject: 'Data Analysis Project', content: 'I need help with analyzing customer behavior data.', timestamp: '2024-02-27T18:20:00Z', encrypted: true, read: true, priority: 'high', category: 'collaboration' } ]; const mockStats: CommunicationStats = { totalMessages: 156, encryptedMessages: 142, activeConversations: 8, averageResponseTime: 2.3, reputationScore: 8500, messagesByCategory: { direct: 45, collaboration: 67, marketplace: 28, system: 16 }, weeklyActivity: [ { day: 'Mon', messages: 23, encryption: 21 }, { day: 'Tue', messages: 31, encryption: 28 }, { day: 'Wed', messages: 28, encryption: 26 }, { day: 'Thu', messages: 35, encryption: 32 }, { day: 'Fri', messages: 29, encryption: 27 }, { day: 'Sat', messages: 10, encryption: 8 }, { day: 'Sun', messages: 0, encryption: 0 } ] }; useEffect(() => { // Load mock data setTimeout(() => { setConversations(mockConversations); setMessages(mockMessages); setStats(mockStats); setLoading(false); }, 1000); }, [address]); const handleSendMessage = async () => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to send messages", variant: "destructive" }); return; } if (!newMessage.trim() || !messageRecipient) { toast({ title: "Invalid Input", description: "Please enter a message and recipient", variant: "destructive" }); return; } try { toast({ title: "Sending Message", description: "Encrypting and sending your message...", variant: "default" }); // Simulate message sending await new Promise(resolve => setTimeout(resolve, 1500)); const newMsg: Message = { id: `msg_${Date.now()}`, sender: address || '0x1234...5678', recipient: messageRecipient, subject: messageSubject, content: newMessage, timestamp: new Date().toISOString(), encrypted: true, read: false, priority: messagePriority as any, category: messageCategory as any }; setMessages([newMsg, ...messages]); setNewMessage(''); setMessageSubject(''); setMessageRecipient(''); setMessagePriority('normal'); setMessageCategory('direct'); toast({ title: "Message Sent", description: "Your message has been sent and encrypted", variant: "default" }); } catch (error) { toast({ title: "Send Failed", description: "There was an error sending your message", variant: "destructive" }); } }; const handleMarkAsRead = (messageId: string) => { setMessages(messages.map(msg => msg.id === messageId ? { ...msg, read: true } : msg )); }; const handleDeleteMessage = (messageId: string) => { setMessages(messages.filter(msg => msg.id !== messageId)); toast({ title: "Message Deleted", description: "The message has been deleted", variant: "default" }); }; const getPriorityColor = (priority: string) => { switch (priority) { case 'urgent': return 'bg-red-500'; case 'high': return 'bg-orange-500'; case 'normal': return 'bg-blue-500'; case 'low': return 'bg-gray-500'; default: return 'bg-gray-400'; } }; const getCategoryIcon = (category: string) => { switch (category) { case 'direct': return ; case 'collaboration': return ; case 'marketplace': return ; case 'system': return ; default: return ; } }; const getStatusColor = (status: string) => { switch (status) { case 'online': return 'bg-green-500'; case 'busy': return 'bg-yellow-500'; case 'offline': return 'bg-gray-400'; default: return 'bg-gray-400'; } }; const filteredConversations = conversations.filter(conv => { if (searchQuery) { const query = searchQuery.toLowerCase(); return conv.participants.some(p => p.name.toLowerCase().includes(query) || p.address.toLowerCase().includes(query) ); } if (filterCategory !== 'all') { return conv.category === filterCategory; } if (showEncryptedOnly) { return conv.encrypted; } return true; }); if (loading) { return (

Loading agent communication...

); } return (

Agent Communication

Secure agent-to-agent messaging with reputation-based access control

{stats?.totalMessages} Messages {stats?.encryptedMessages} Encrypted {stats?.activeConversations} Active
Conversations Messages Compose Analytics {/* Search and Filters */} Search & Filter
setSearchQuery(e.target.value)} className="pl-10" />
setShowEncryptedOnly(e.target.checked)} className="rounded" />
{/* Conversations List */}
{filteredConversations.map((conversation) => (
{getCategoryIcon(conversation.category)} {conversation.category} {conversation.encrypted && ( Encrypted )} {conversation.unreadCount > 0 && ( {conversation.unreadCount} )}
{conversation.participants.slice(0, 3).map((participant, index) => (
{participant.avatar || participant.name.charAt(0).toUpperCase()}
))}
{conversation.participants.map(p => p.name).join(', ')}
{conversation.participants[1]?.status} • {conversation.participants[1]?.reputation.toLocaleString()} rep

{conversation.lastMessage.content}

{conversation.lastMessage.sender === address ? 'You' : conversation.participants[1]?.name} {new Date(conversation.lastMessage.timestamp).toLocaleTimeString()}
{conversation.tags.length > 0 && (
{conversation.tags.map((tag, index) => ( #{tag} ))}
)}
))}
Messages All your agent communications in one place
{messages.map((message) => (
{message.subject} {message.encrypted && ( Encrypted )} {!message.read && ( Unread )}
{new Date(message.timestamp).toLocaleString()}
From:

{message.sender}

To:

{message.recipient}

{message.content}

{message.category} {message.priority}
{!message.read && ( )}
))}
Compose Message Send a secure message to another agent
setMessageRecipient(e.target.value)} />
setMessageSubject(e.target.value)} />