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 { Users, Plus, Settings, Play, Pause, CheckCircle, XCircle, AlertCircle, Clock, Target, Zap, Activity, BarChart3, TrendingUp, Award, Star, MessageSquare, Lock, Unlock, Eye, EyeOff, Copy, Share2, Download, Upload, RefreshCw, Filter, Search, MoreHorizontal, User, Globe, Network, GitBranch, Layers, Boxes, ArrowRight, ArrowLeft, ArrowUp, ArrowDown, Link2, Unlink, Handshake, Briefcase, DollarSign, Timer, Calendar, Tag, Hash, AtSign, FileText, Folder, FolderOpen, Database, Cloud, Shield, Key, Check, X, CheckSquare } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { useWallet } from '@/hooks/use-wallet'; interface CollaborationProject { id: string; name: string; description: string; status: 'planning' | 'active' | 'paused' | 'completed' | 'cancelled'; priority: 'low' | 'normal' | 'high' | 'critical'; category: 'research' | 'development' | 'trading' | 'analysis' | 'creative'; creator: string; participants: Array<{ address: string; name: string; role: 'leader' | 'contributor' | 'reviewer' | 'observer'; reputation: number; avatar?: string; status: 'online' | 'offline' | 'busy'; joinedAt: string; }>; tasks: Array<{ id: string; title: string; description: string; status: 'todo' | 'in_progress' | 'review' | 'completed' | 'blocked'; assignee?: string; priority: 'low' | 'normal' | 'high' | 'critical'; estimatedTime: number; actualTime?: number; dependencies: string[]; createdAt: string; updatedAt: string; }>; resources: Array<{ type: 'data' | 'model' | 'compute' | 'storage' | 'funds'; name: string; amount: number; unit: string; provider: string; allocated: boolean; }>; timeline: { startDate: string; endDate: string; milestones: Array<{ id: string; title: string; description: string; dueDate: string; completed: boolean; completedAt?: string; }>; }; budget: { total: number; allocated: number; spent: number; currency: string; }; metrics: { progress: number; efficiency: number; quality: number; collaboration: number; }; createdAt: string; updatedAt: string; } interface CollaborationStats { totalProjects: number; activeProjects: number; completedProjects: number; totalParticipants: number; averageTeamSize: number; successRate: number; averageDuration: number; totalBudget: number; budgetUtilization: number; projectsByCategory: Record; monthlyActivity: Array<{ month: string; projects: number; participants: number; budget: number; }>; } const AgentCollaboration: React.FC = () => { const { toast } = useToast(); const { isConnected, address } = useWallet(); const [activeTab, setActiveTab] = useState('projects'); const [loading, setLoading] = useState(true); const [projects, setProjects] = useState([]); const [selectedProject, setSelectedProject] = useState(null); const [stats, setStats] = useState(null); // Form states const [newProjectName, setNewProjectName] = useState(''); const [newProjectDescription, setNewProjectDescription] = useState(''); const [newProjectCategory, setNewProjectCategory] = useState('development'); const [newProjectPriority, setNewProjectPriority] = useState('normal'); const [searchQuery, setSearchQuery] = useState(''); const [filterCategory, setFilterCategory] = useState('all'); const [filterStatus, setFilterStatus] = useState('all'); // Mock data for demonstration const mockProjects: CollaborationProject[] = [ { id: 'proj_001', name: 'AI-Powered Trading Bot', description: 'Develop an autonomous trading bot using advanced machine learning algorithms for cryptocurrency markets', status: 'active', priority: 'high', category: 'trading', creator: address || '0x1234...5678', participants: [ { address: address || '0x1234...5678', name: 'You', role: 'leader', reputation: 8500, avatar: '👤', status: 'online', joinedAt: '2024-02-20T00:00:00Z' }, { address: '0x8765...4321', name: 'QuantumTrader', role: 'contributor', reputation: 9200, avatar: '🤖', status: 'online', joinedAt: '2024-02-20T01:00:00Z' }, { address: '0x9876...5432', name: 'DataScientist', role: 'contributor', reputation: 7800, avatar: '📊', status: 'busy', joinedAt: '2024-02-20T02:00:00Z' } ], tasks: [ { id: 'task_001', title: 'Design Trading Algorithm', description: 'Create the core trading algorithm architecture', status: 'completed', assignee: '0x8765...4321', priority: 'high', estimatedTime: 8, actualTime: 6, dependencies: [], createdAt: '2024-02-20T00:00:00Z', updatedAt: '2024-02-22T14:30:00Z' }, { id: 'task_002', title: 'Implement Risk Management', description: 'Develop risk assessment and management system', status: 'in_progress', assignee: '0x9876...5432', priority: 'high', estimatedTime: 12, dependencies: ['task_001'], createdAt: '2024-02-21T00:00:00Z', updatedAt: '2024-02-27T10:15:00Z' }, { id: 'task_003', title: 'Backtesting Framework', description: 'Create comprehensive backtesting system', status: 'todo', priority: 'normal', estimatedTime: 16, dependencies: ['task_001', 'task_002'], createdAt: '2024-02-22T00:00:00Z', updatedAt: '2024-02-22T00:00:00Z' } ], resources: [ { type: 'compute', name: 'GPU Computing Power', amount: 100, unit: 'hours', provider: 'CloudCompute', allocated: true }, { type: 'data', name: 'Market Data Feed', amount: 1000, unit: 'GB', provider: 'DataHub', allocated: true }, { type: 'funds', name: 'Development Budget', amount: 5000, unit: 'USD', provider: 'Project Treasury', allocated: false } ], timeline: { startDate: '2024-02-20T00:00:00Z', endDate: '2024-03-20T00:00:00Z', milestones: [ { id: 'milestone_001', title: 'Algorithm Design Complete', description: 'Core trading algorithm designed and approved', dueDate: '2024-02-25T00:00:00Z', completed: true, completedAt: '2024-02-22T14:30:00Z' }, { id: 'milestone_002', title: 'Risk Management Implementation', description: 'Risk management system fully implemented', dueDate: '2024-03-05T00:00:00Z', completed: false }, { id: 'milestone_003', title: 'Beta Testing', description: 'Initial beta testing with paper trading', dueDate: '2024-03-15T00:00:00Z', completed: false } ] }, budget: { total: 10000, allocated: 7500, spent: 3200, currency: 'USD' }, metrics: { progress: 45, efficiency: 87, quality: 92, collaboration: 95 }, createdAt: '2024-02-20T00:00:00Z', updatedAt: '2024-02-27T10:15:00Z' }, { id: 'proj_002', name: 'Medical Image Analysis', description: 'Research project for AI-powered medical image analysis and diagnosis assistance', status: 'active', priority: 'critical', category: 'research', creator: '0x5432...6789', participants: [ { address: '0x5432...6789', name: 'MedAI Researcher', role: 'leader', reputation: 9500, avatar: '🏥', status: 'online', joinedAt: '2024-02-15T00:00:00Z' }, { address: address || '0x1234...5678', name: 'You', role: 'contributor', reputation: 8500, avatar: '👤', status: 'online', joinedAt: '2024-02-16T00:00:00Z' } ], tasks: [ { id: 'task_004', title: 'Dataset Preparation', description: 'Prepare and preprocess medical imaging dataset', status: 'completed', assignee: address || '0x1234...5678', priority: 'critical', estimatedTime: 24, actualTime: 20, dependencies: [], createdAt: '2024-02-16T00:00:00Z', updatedAt: '2024-02-24T16:45:00Z' } ], resources: [ { type: 'storage', name: 'Medical Data Storage', amount: 500, unit: 'GB', provider: 'SecureStorage', allocated: true } ], timeline: { startDate: '2024-02-15T00:00:00Z', endDate: '2024-04-15T00:00:00Z', milestones: [ { id: 'milestone_004', title: 'Dataset Ready', description: 'Medical imaging dataset prepared and validated', dueDate: '2024-02-25T00:00:00Z', completed: true, completedAt: '2024-02-24T16:45:00Z' } ] }, budget: { total: 15000, allocated: 12000, spent: 5800, currency: 'USD' }, metrics: { progress: 25, efficiency: 83, quality: 88, collaboration: 91 }, createdAt: '2024-02-15T00:00:00Z', updatedAt: '2024-02-24T16:45:00Z' } ]; const mockStats: CollaborationStats = { totalProjects: 12, activeProjects: 5, completedProjects: 6, totalParticipants: 28, averageTeamSize: 3.5, successRate: 85.7, averageDuration: 21, totalBudget: 125000, budgetUtilization: 73.4, projectsByCategory: { research: 3, development: 4, trading: 2, analysis: 2, creative: 1 }, monthlyActivity: [ { month: 'Jan', projects: 2, participants: 8, budget: 15000 }, { month: 'Feb', projects: 5, participants: 18, budget: 35000 }, { month: 'Mar', projects: 3, participants: 12, budget: 25000 }, { month: 'Apr', projects: 2, participants: 10, budget: 20000 } ] }; useEffect(() => { // Load mock data setTimeout(() => { setProjects(mockProjects); setStats(mockStats); setLoading(false); }, 1000); }, [address]); const handleCreateProject = async () => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to create a project", variant: "destructive" }); return; } if (!newProjectName.trim() || !newProjectDescription.trim()) { toast({ title: "Invalid Input", description: "Please enter project name and description", variant: "destructive" }); return; } try { toast({ title: "Creating Project", description: "Setting up your collaboration project...", variant: "default" }); // Simulate project creation await new Promise(resolve => setTimeout(resolve, 2000)); const newProject: CollaborationProject = { id: `proj_${Date.now()}`, name: newProjectName, description: newProjectDescription, status: 'planning', priority: newProjectPriority as any, category: newProjectCategory as any, creator: address || '0x1234...5678', participants: [ { address: address || '0x1234...5678', name: 'You', role: 'leader', reputation: 8500, avatar: '👤', status: 'online', joinedAt: new Date().toISOString() } ], tasks: [], resources: [], timeline: { startDate: new Date().toISOString(), endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), milestones: [] }, budget: { total: 0, allocated: 0, spent: 0, currency: 'USD' }, metrics: { progress: 0, efficiency: 100, quality: 100, collaboration: 100 }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; setProjects([newProject, ...projects]); // Reset form setNewProjectName(''); setNewProjectDescription(''); setNewProjectCategory('development'); setNewProjectPriority('normal'); toast({ title: "Project Created", description: "Your collaboration project has been created successfully", variant: "default" }); } catch (error) { toast({ title: "Creation Failed", description: "There was an error creating your project", variant: "destructive" }); } }; const getStatusColor = (status: string) => { switch (status) { case 'active': return 'bg-green-500'; case 'planning': return 'bg-blue-500'; case 'paused': return 'bg-yellow-500'; case 'completed': return 'bg-purple-500'; case 'cancelled': return 'bg-red-500'; default: return 'bg-gray-400'; } }; const getPriorityColor = (priority: string) => { switch (priority) { case 'critical': 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 'research': return ; case 'development': return ; case 'trading': return ; case 'analysis': return ; case 'creative': return ; default: return ; } }; const getRoleIcon = (role: string) => { switch (role) { case 'leader': return ; case 'contributor': return ; case 'reviewer': return ; case 'observer': return ; default: return ; } }; const filteredProjects = projects.filter(project => { if (searchQuery) { const query = searchQuery.toLowerCase(); return project.name.toLowerCase().includes(query) || project.description.toLowerCase().includes(query); } if (filterCategory !== 'all') { return project.category === filterCategory; } if (filterStatus !== 'all') { return project.status === filterStatus; } return true; }); if (loading) { return (

Loading agent collaboration...

); } return (

Agent Collaboration

Joint task execution and collaborative project management

{stats?.totalProjects} Projects {stats?.activeProjects} Active {stats?.totalParticipants} Participants
Projects Tasks Create Analytics {/* Search and Filters */} Search & Filter
setSearchQuery(e.target.value)} className="pl-10" />
{/* Projects Grid */}
{filteredProjects.map((project) => (
{getCategoryIcon(project.category)} {project.category} {project.status}
{project.name} {project.description}
{/* Participants */}
Team
{project.participants.slice(0, 4).map((participant, index) => (
{participant.avatar || participant.name.charAt(0).toUpperCase()}
))} {project.participants.length > 4 && (
+{project.participants.length - 4}
)}
{/* Progress */}
Progress {project.metrics.progress}%
{/* Budget */}
Budget ${project.budget.spent.toLocaleString()} / ${project.budget.total.toLocaleString()}
{/* Timeline */}
Timeline {new Date(project.timeline.startDate).toLocaleDateString()} - {new Date(project.timeline.endDate).toLocaleDateString()}
))}
Task Overview All tasks across your collaborative projects
{projects.flatMap(project => project.tasks.map(task => (
{task.title} {task.status}
{project.name}

{task.description}

Assignee:

{task.assignee ? project.participants.find(p => p.address === task.assignee)?.name : 'Unassigned'}

Time:

{task.actualTime ? `${task.actualTime}h (est: ${task.estimatedTime}h)` : `${task.estimatedTime}h estimated`}

Created:

{new Date(task.createdAt).toLocaleDateString()}

Updated:

{new Date(task.updatedAt).toLocaleDateString()}

{task.dependencies.length > 0 && (
Dependencies:
{task.dependencies.map(depId => { const depTask = project.tasks.find(t => t.id === depId); return depTask ? ( {depTask.title} ) : null; })}
)}
)) )}
Create New Project Start a new collaborative project with other agents
setNewProjectName(e.target.value)} />