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 { Store, TrendingUp, Users, Package, Star, Heart, Share2, Download, Upload, Search, Filter, Plus, Edit, Trash2, Eye, EyeOff, Copy, MoreHorizontal, Clock, Calendar, DollarSign, CreditCard, Wallet, Shield, Lock, Unlock, CheckCircle, XCircle, AlertCircle, Info, BarChart3, Activity, Zap, Rocket, Target, Award, Crown, Gem, Sparkles, Settings, Play, Pause, RefreshCw, ArrowRight, ArrowUp, ArrowDown, ChevronRight, ChevronDown, ShoppingBag, ShoppingCart, Tag, Hash, AtSign, User, Building, Globe, Network, Database, Cloud, Cpu, HardDrive, MemoryStick, Wifi, Battery, Gauge, LineChart, PieChart, FileText, Folder, FolderOpen, Bell, Volume2, VolumeX, MessageSquare, ThumbsUp, ThumbsDown, Bookmark, BookmarkCheck, Link2, Unlink, ZapOff, Power, PowerOff, Settings2, Sliders, ToggleLeft, ToggleRight, Key, EyeOff as EyeHidden, Copy as CopyIcon, Share as ShareIcon, Brain } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { useWallet } from '@/hooks/use-wallet'; interface MarketplaceService { id: string; name: string; description: string; type: 'capability' | 'service' | 'subscription' | 'model' | 'compute' | 'data'; category: string; provider: { address: string; name: string; reputation: number; avatar?: string; verified: boolean; }; pricing: { type: 'fixed' | 'subscription' | 'usage_based' | 'auction'; amount: number; currency: string; period?: string; unit?: string; discount?: number; }; capabilities: Array<{ name: string; description: string; performance: number; reliability: number; }>; metrics: { rating: number; reviews: number; usage: number; revenue: number; subscribers?: number; }; availability: { status: 'available' | 'busy' | 'offline' | 'maintenance'; uptime: number; responseTime: number; lastUpdated: string; }; requirements: { minReputation: number; supportedChains: string[]; prerequisites: string[]; }; metadata: { tags: string[]; createdAt: string; updatedAt: string; version: string; documentation?: string; }; } interface MarketplaceStats { totalServices: number; activeProviders: number; totalRevenue: number; averageRating: number; totalTransactions: number; activeSubscriptions: number; servicesByType: Record; servicesByCategory: Record; topProviders: Array<{ name: string; revenue: number; services: number; rating: number; }>; monthlyActivity: Array<{ month: string; services: number; revenue: number; transactions: number; users: number; }>; } const MarketplaceV2: React.FC = () => { const { toast } = useToast(); const { isConnected, address } = useWallet(); const [activeTab, setActiveTab] = useState('marketplace'); const [loading, setLoading] = useState(true); const [services, setServices] = useState([]); const [selectedService, setSelectedService] = useState(null); const [stats, setStats] = useState(null); // Form states const [newServiceName, setNewServiceName] = useState(''); const [newServiceType, setNewServiceType] = useState('capability'); const [newServiceCategory, setNewServiceCategory] = useState('ai'); const [newServiceDescription, setNewServiceDescription] = useState(''); const [newServicePrice, setNewServicePrice] = useState(''); const [newServicePricingType, setNewServicePricingType] = useState('fixed'); const [searchQuery, setSearchQuery] = useState(''); const [filterType, setFilterType] = useState('all'); const [filterCategory, setFilterCategory] = useState('all'); const [sortBy, setSortBy] = useState('rating'); // Mock data const mockServices: MarketplaceService[] = [ { id: 'service_001', name: 'Quantum Trading Algorithm', description: 'Advanced reinforcement learning algorithm for cryptocurrency trading with 95% accuracy', type: 'capability', category: 'trading', provider: { address: '0x8765...4321', name: 'QuantumTrader Pro', reputation: 9200, avatar: '🤖', verified: true }, pricing: { type: 'subscription', amount: 500, currency: 'USDT', period: 'monthly', discount: 10 }, capabilities: [ { name: 'Market Analysis', description: 'Real-time market analysis', performance: 95, reliability: 98 }, { name: 'Risk Management', description: 'Advanced risk assessment', performance: 92, reliability: 96 }, { name: 'Order Execution', description: 'Automated order execution', performance: 94, reliability: 99 } ], metrics: { rating: 4.8, reviews: 234, usage: 1520, revenue: 125000, subscribers: 89 }, availability: { status: 'available', uptime: 99.8, responseTime: 45, lastUpdated: '2024-02-27T10:15:00Z' }, requirements: { minReputation: 1000, supportedChains: ['ethereum', 'polygon', 'bnb'], prerequisites: ['Wallet connected', 'Minimum 1000 USDT'] }, metadata: { tags: ['trading', 'ai', 'reinforcement-learning', 'crypto'], createdAt: '2024-02-01T00:00:00Z', updatedAt: '2024-02-27T10:15:00Z', version: '2.1.0', documentation: 'https://docs.quantumtrader.ai' } }, { id: 'service_002', name: 'Medical Image Analysis AI', description: 'Deep learning model for medical image analysis and diagnosis assistance', type: 'model', category: 'healthcare', provider: { address: '0x5432...6789', name: 'MedAI Solutions', reputation: 8900, avatar: '🏥', verified: true }, pricing: { type: 'usage_based', amount: 0.05, currency: 'USDT', unit: 'image' }, capabilities: [ { name: 'Image Classification', description: 'Medical image classification', performance: 94, reliability: 97 }, { name: 'Anomaly Detection', description: 'Detect anomalies in medical images', performance: 91, reliability: 95 } ], metrics: { rating: 4.6, reviews: 156, usage: 890, revenue: 45600 }, availability: { status: 'available', uptime: 99.5, responseTime: 120, lastUpdated: '2024-02-27T09:30:00Z' }, requirements: { minReputation: 500, supportedChains: ['ethereum', 'polygon'], prerequisites: ['HIPAA compliance', 'Medical license verification'] }, metadata: { tags: ['healthcare', 'ai', 'medical', 'diagnosis'], createdAt: '2024-02-10T00:00:00Z', updatedAt: '2024-02-27T09:30:00Z', version: '1.3.0' } }, { id: 'service_003', name: 'GPU Compute Power', description: 'High-performance GPU computing for AI training and inference', type: 'compute', category: 'infrastructure', provider: { address: '0x9876...5432', name: 'CloudCompute Pro', reputation: 8700, avatar: '☁️', verified: true }, pricing: { type: 'usage_based', amount: 0.50, currency: 'USDT', unit: 'hour' }, capabilities: [ { name: 'GPU Processing', description: 'NVIDIA A100 GPU access', performance: 98, reliability: 99 }, { name: 'High Memory', description: '80GB VRAM available', performance: 96, reliability: 98 } ], metrics: { rating: 4.7, reviews: 412, usage: 2340, revenue: 289000 }, availability: { status: 'available', uptime: 99.9, responseTime: 5, lastUpdated: '2024-02-27T11:00:00Z' }, requirements: { minReputation: 100, supportedChains: ['ethereum', 'polygon', 'bnb', 'arbitrum'], prerequisites: ['None'] }, metadata: { tags: ['compute', 'gpu', 'infrastructure', 'ai'], createdAt: '2024-01-15T00:00:00Z', updatedAt: '2024-02-27T11:00:00Z', version: '3.0.0' } } ]; const mockStats: MarketplaceStats = { totalServices: 156, activeProviders: 42, totalRevenue: 2847500, averageRating: 4.5, totalTransactions: 12450, activeSubscriptions: 892, servicesByType: { capability: 45, service: 38, subscription: 29, model: 22, compute: 15, data: 7 }, servicesByCategory: { ai: 68, trading: 32, healthcare: 18, infrastructure: 15, data: 12, other: 11 }, topProviders: [ { name: 'QuantumTrader Pro', revenue: 125000, services: 3, rating: 4.8 }, { name: 'CloudCompute Pro', revenue: 289000, services: 5, rating: 4.7 }, { name: 'MedAI Solutions', revenue: 45600, services: 2, rating: 4.6 } ], monthlyActivity: [ { month: 'Jan', services: 12, revenue: 450000, transactions: 2100, users: 340 }, { month: 'Feb', services: 18, revenue: 680000, transactions: 3200, users: 520 }, { month: 'Mar', services: 24, revenue: 890000, transactions: 4100, users: 680 }, { month: 'Apr', services: 28, revenue: 827500, transactions: 3050, users: 590 } ] }; useEffect(() => { setTimeout(() => { setServices(mockServices); setStats(mockStats); setLoading(false); }, 1000); }, [address]); const handlePurchaseService = async (serviceId: string) => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to purchase services", variant: "destructive" }); return; } try { toast({ title: "Processing Purchase", description: "Initiating service purchase...", variant: "default" }); await new Promise(resolve => setTimeout(resolve, 2000)); toast({ title: "Purchase Successful", description: "Service has been added to your account", variant: "default" }); } catch (error) { toast({ title: "Purchase Failed", description: "There was an error processing your purchase", variant: "destructive" }); } }; const handleSubscribeService = async (serviceId: string) => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to subscribe", variant: "destructive" }); return; } try { toast({ title: "Processing Subscription", description: "Setting up your subscription...", variant: "default" }); await new Promise(resolve => setTimeout(resolve, 2000)); toast({ title: "Subscription Active", description: "You are now subscribed to this service", variant: "default" }); } catch (error) { toast({ title: "Subscription Failed", description: "There was an error setting up your subscription", variant: "destructive" }); } }; const handleListService = async () => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to list services", variant: "destructive" }); return; } if (!newServiceName.trim() || !newServiceDescription.trim() || !newServicePrice) { toast({ title: "Invalid Input", description: "Please fill in all required fields", variant: "destructive" }); return; } try { toast({ title: "Listing Service", description: "Publishing your service to the marketplace...", variant: "default" }); await new Promise(resolve => setTimeout(resolve, 2000)); const newService: MarketplaceService = { id: `service_${Date.now()}`, name: newServiceName, description: newServiceDescription, type: newServiceType as any, category: newServiceCategory, provider: { address: address || '0x1234...5678', name: 'You', reputation: 8500, verified: false }, pricing: { type: newServicePricingType as any, amount: parseFloat(newServicePrice), currency: 'USDT', period: newServicePricingType === 'subscription' ? 'monthly' : undefined, unit: newServicePricingType === 'usage_based' ? 'unit' : undefined }, capabilities: [], metrics: { rating: 0, reviews: 0, usage: 0, revenue: 0 }, availability: { status: 'available', uptime: 0, responseTime: 0, lastUpdated: new Date().toISOString() }, requirements: { minReputation: 0, supportedChains: ['ethereum'], prerequisites: [] }, metadata: { tags: [], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), version: '1.0.0' } }; setServices([newService, ...services]); // Reset form setNewServiceName(''); setNewServiceType('capability'); setNewServiceCategory('ai'); setNewServiceDescription(''); setNewServicePrice(''); setNewServicePricingType('fixed'); toast({ title: "Service Listed", description: "Your service is now live on the marketplace", variant: "default" }); } catch (error) { toast({ title: "Listing Failed", description: "There was an error listing your service", variant: "destructive" }); } }; const getStatusColor = (status: string) => { switch (status) { case 'available': return 'bg-green-500'; case 'busy': return 'bg-yellow-500'; case 'offline': return 'bg-red-500'; case 'maintenance': return 'bg-orange-500'; default: return 'bg-gray-400'; } }; const getTypeIcon = (type: string) => { switch (type) { case 'capability': return ; case 'service': return ; case 'subscription': return ; case 'model': return ; case 'compute': return ; case 'data': return ; default: return ; } }; const getRatingColor = (rating: number) => { if (rating >= 4.5) return 'text-green-600'; if (rating >= 4.0) return 'text-blue-600'; if (rating >= 3.5) return 'text-yellow-600'; return 'text-red-600'; }; const sortedServices = [...services].sort((a, b) => { switch (sortBy) { case 'rating': return b.metrics.rating - a.metrics.rating; case 'revenue': return b.metrics.revenue - a.metrics.revenue; case 'usage': return b.metrics.usage - a.metrics.usage; case 'price_low': return a.pricing.amount - b.pricing.amount; case 'price_high': return b.pricing.amount - a.pricing.amount; case 'name': return a.name.localeCompare(b.name); default: return 0; } }); const filteredServices = sortedServices.filter(service => { if (searchQuery) { const query = searchQuery.toLowerCase(); return service.name.toLowerCase().includes(query) || service.description.toLowerCase().includes(query) || service.provider.name.toLowerCase().includes(query); } if (filterType !== 'all') return service.type === filterType; if (filterCategory !== 'all') return service.category === filterCategory; return true; }); if (loading) { return (

Loading Agent Marketplace 2.0...

); } return (

Agent Marketplace 2.0

Advanced agent capability trading and service subscriptions

{stats?.totalServices} Services {stats?.activeProviders} Providers {stats?.averageRating} Avg Rating
Marketplace Subscriptions List Service Analytics {/* Search and Filters */} Search & Filter
setSearchQuery(e.target.value)} className="pl-10" />
{/* Services Grid */}
{filteredServices.map((service) => (
{getTypeIcon(service.type)} {service.type} {service.category} {service.provider.verified && ( Verified )}
{service.name} {service.description}
{/* Provider Info */}
{service.provider.avatar || service.provider.name.charAt(0).toUpperCase()}
{service.provider.name} {service.provider.reputation.toLocaleString()} rep
{service.metrics.rating} ({service.metrics.reviews})
{/* Pricing */}
Pricing
${service.pricing.amount} {service.pricing.currency}
{service.pricing.type === 'subscription' && `per ${service.pricing.period}`} {service.pricing.type === 'usage_based' && `per ${service.pricing.unit}`} {service.pricing.type === 'fixed' && 'one-time'} {service.pricing.type === 'auction' && 'auction'}
{/* Metrics */}
{service.metrics.usage.toLocaleString()}
Usage
{service.availability.uptime}%
Uptime
{service.availability.responseTime}ms
Response
{/* Tags */} {service.metadata.tags.length > 0 && (
{service.metadata.tags.slice(0, 3).map((tag, index) => ( #{tag} ))} {service.metadata.tags.length > 3 && ( +{service.metadata.tags.length - 3} )}
)}
{service.pricing.type === 'subscription' ? ( ) : ( )}
))}
Active Subscriptions Your active service subscriptions
{services.filter(s => s.pricing.type === 'subscription').map((service) => (
{getTypeIcon(service.type)} {service.name} {service.provider.name}
Active

{service.description}

Monthly Cost:

${service.pricing.amount} {service.pricing.currency}

Next Billing:

March 27, 2024

Usage This Month:

{Math.floor(service.metrics.usage * 0.3)} times

Status:

Active

))}
List New Service Offer your services on the Agent Marketplace 2.0
setNewServiceName(e.target.value)} />