"use client";
import React, { useState, useEffect } from "react";
import Link from 'next/link';
import {
  Brain, Database, TrendingUp, Monitor, Rocket, Cpu, Settings, 
  PlayCircle, Lightbulb, Atom, Signal, Globe, IterationCw, 
  Zap, BrainCircuit, SlidersHorizontal, MessageSquare, 
  FlaskConical, Microscope, Target, Gauge, Cloud, Layers,
  BookOpen, Search, Filter, Grid, List, Star, Clock,
  Activity, BarChart3, Users, Workflow, Code, Sparkles,
  Shield, Lock, Eye, Download, Upload, Save, Settings2,
  ChevronRight, Plus, Minus, X, Check, AlertCircle,
  Heart, Trophy, Flame, Wand2, Box, Share2, Wrench, Server
} from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

const platformApps = [
  // Core Training & Data
  {
    id: "train-model",
    href: "/deep-learning/train",
    title: "Model Training",
    description: "Configure and launch ZPE-enhanced neural network training jobs with quantum optimization",
    icon: PlayCircle,
    category: "core",
    status: "online",
    users: "2.1k",
    gradient: "from-emerald-500 to-teal-600",
    bgGradient: "from-emerald-50 to-teal-50",
    darkBgGradient: "from-emerald-950/20 to-teal-950/20",
    badge: "Popular",
    badgeColor: "bg-emerald-500"
  },
  {
    id: "data-portal",
    href: "/deep-learning/data-portal",
    title: "Data Portal",
    description: "Access, manage, and preprocess massive training datasets with quantum-enhanced indexing",
    icon: Database,
    category: "core",
    status: "online",
    users: "1.8k",
    gradient: "from-blue-500 to-cyan-600",
    bgGradient: "from-blue-50 to-cyan-50",
    darkBgGradient: "from-blue-950/20 to-cyan-950/20",
    badge: "Essential",
    badgeColor: "bg-blue-500"
  },
  {
    id: "performance",
    href: "/deep-learning/performance",
    title: "Performance Analytics",
    description: "Real-time training metrics, model health analysis, and quantum convergence tracking",
    icon: TrendingUp,
    category: "analytics",
    status: "online",
    users: "1.5k",
    gradient: "from-purple-500 to-violet-600",
    bgGradient: "from-purple-50 to-violet-50",
    darkBgGradient: "from-purple-950/20 to-violet-950/20",
    badge: "Pro",
    badgeColor: "bg-purple-500"
  },
  {
    id: "gpu-monitor",
    href: "/deep-learning/gpu-monitor",
    title: "GPU Monitor",
    description: "Live hardware statistics, thermal management, and quantum processing unit diagnostics",
    icon: Monitor,
    category: "infrastructure",
    status: "online",
    users: "980",
    gradient: "from-orange-500 to-red-600",
    bgGradient: "from-orange-50 to-red-50",
    darkBgGradient: "from-orange-950/20 to-red-950/20",
    badge: "Critical",
    badgeColor: "bg-orange-500"
  },

  // AI & Intelligence
  {
    id: "ai-flows",
    href: "/deep-learning/ai",
    title: "AI Flows Hub",
    description: "Advanced GenAI-powered tools, workflow automation, and intelligent optimization systems",
    icon: Rocket,
    category: "ai",
    status: "online",
    users: "2.5k",
    gradient: "from-pink-500 to-rose-600",
    bgGradient: "from-pink-50 to-rose-50",
    darkBgGradient: "from-pink-950/20 to-rose-950/20",
    badge: "Featured",
    badgeColor: "bg-pink-500"
  },
  {
    id: "ai-assistant",
    href: "/deep-learning/ai-analysis",
    title: "AI Assistant",
    description: "Intelligent chat interface for model insights, optimization suggestions, and troubleshooting",
    icon: MessageSquare,
    category: "ai",
    status: "online",
    users: "1.9k",
    gradient: "from-indigo-500 to-blue-600",
    bgGradient: "from-indigo-50 to-blue-50",
    darkBgGradient: "from-indigo-950/20 to-blue-950/20",
    badge: "Smart",
    badgeColor: "bg-indigo-500"
  },
  {
    id: "architecture",
    href: "/deep-learning/architecture",
    title: "Architecture Designer",
    description: "Visual neural network architect with quantum layer composition and topology optimization",
    icon: Layers,
    category: "design",
    status: "online",
    users: "1.2k",
    gradient: "from-teal-500 to-green-600",
    bgGradient: "from-teal-50 to-green-50",
    darkBgGradient: "from-teal-950/20 to-green-950/20",
    badge: "Pro",
    badgeColor: "bg-teal-500"
  },

  // Quantum & Advanced
  {
    id: "zpe-flow",
    href: "/deep-learning/zpe-flow",
    title: "HS-QNN Advisor",
    description: "Hilbert Space Quantum Neural Network parameter optimization and dimensional analysis",
    icon: BrainCircuit,
    category: "quantum",
    status: "online",
    users: "890",
    gradient: "from-violet-500 to-purple-600",
    bgGradient: "from-violet-50 to-purple-50",
    darkBgGradient: "from-violet-950/20 to-purple-950/20",
    badge: "Advanced",
    badgeColor: "bg-violet-500"
  },
  {
    id: "zpe-flow-analysis",
    href: "/deep-learning/zpe-flow-analysis",
    title: "ZPE Flow Analysis",
    description: "Interactive zero-point energy flow visualization and quantum field parameter tuning",
    icon: SlidersHorizontal,
    category: "quantum",
    status: "online",
    users: "756",
    gradient: "from-cyan-500 to-blue-600",
    bgGradient: "from-cyan-50 to-blue-50",
    darkBgGradient: "from-cyan-950/20 to-blue-950/20",
    badge: "Quantum",
    badgeColor: "bg-cyan-500"
  },
  {
    id: "quantum-noise",
    href: "/deep-learning/quantum-noise",
    title: "Quantum Noise Gen",
    description: "Generate and analyze quantum-derived noise patterns for enhanced training robustness",
    icon: Atom,
    category: "quantum",
    status: "online",
    users: "634",
    gradient: "from-emerald-500 to-cyan-600",
    bgGradient: "from-emerald-50 to-cyan-50",
    darkBgGradient: "from-emerald-950/20 to-cyan-950/20",
    badge: "Experimental",
    badgeColor: "bg-emerald-500"
  },
  {
    id: "rf-generator",
    href: "/deep-learning/rf-generator",
    title: "RF Generator",
    description: "Radio frequency wave configuration for conceptual network influence and signal processing",
    icon: Signal,
    category: "advanced",
    status: "online",
    users: "445",
    gradient: "from-yellow-500 to-orange-600",
    bgGradient: "from-yellow-50 to-orange-50",
    darkBgGradient: "from-yellow-950/20 to-orange-950/20",
    badge: "Specialized",
    badgeColor: "bg-yellow-500"
  },

  // Visualization & Analysis
  {
    id: "bloch-sphere",
    href: "/deep-learning/vis/bloch-sphere",
    title: "Bloch Sphere",
    description: "3D visualization of qubit states and quantum superposition in Hilbert space",
    icon: Globe,
    category: "visualization",
    status: "online",
    users: "1.1k",
    gradient: "from-blue-500 to-indigo-600",
    bgGradient: "from-blue-50 to-indigo-50",
    darkBgGradient: "from-blue-950/20 to-indigo-950/20",
    badge: "Visual",
    badgeColor: "bg-blue-500"
  },
  {
    id: "dynamic-formation",
    href: "/deep-learning/vis/dynamic-formation",
    title: "Dynamic Formation",
    description: "Real-time visualization of dynamic particle formations and quantum field interactions",
    icon: IterationCw,
    category: "visualization",
    status: "online",
    users: "823",
    gradient: "from-green-500 to-emerald-600",
    bgGradient: "from-green-50 to-emerald-50",
    darkBgGradient: "from-green-950/20 to-emerald-950/20",
    badge: "Live",
    badgeColor: "bg-green-500"
  },
  {
    id: "zpe-particle-sim",
    href: "/deep-learning/vis/zpe-particle-sim",
    title: "ZPE Particle Sim",
    description: "Advanced zero-point energy particle simulation with quantum field dynamics",
    icon: Sparkles,
    category: "visualization",
    status: "beta",
    users: "567",
    gradient: "from-purple-500 to-pink-600",
    bgGradient: "from-purple-50 to-pink-50",
    darkBgGradient: "from-purple-950/20 to-pink-950/20",
    badge: "Beta",
    badgeColor: "bg-purple-500"
  },

  // Infrastructure & Cloud
  {
    id: "cloud-gpu",
    href: "/deep-learning/cloud-gpu",
    title: "Cloud GPU Connect",
    description: "Seamless integration with third-party cloud GPU providers and distributed computing",
    icon: Cloud,
    category: "infrastructure",
    status: "online",
    users: "1.4k",
    gradient: "from-slate-500 to-gray-600",
    bgGradient: "from-slate-50 to-gray-50",
    darkBgGradient: "from-slate-950/20 to-gray-950/20",
    badge: "Cloud",
    badgeColor: "bg-slate-500"
  },
  {
    id: "model-configs",
    href: "/deep-learning/model-configs",
    title: "Model Configurations",
    description: "Centralized model configuration management, versioning, and deployment pipelines",
    icon: Settings,
    category: "management",
    status: "online",
    users: "1.0k",
    gradient: "from-gray-500 to-slate-600",
    bgGradient: "from-gray-50 to-slate-50",
    darkBgGradient: "from-gray-950/20 to-slate-950/20",
    badge: "Config",
    badgeColor: "bg-gray-500"
  },
  {
    id: "my-models",
    href: "/deep-learning/my-zpe-ai-models",
    title: "My ZPE Models",
    description: "Personal model gallery, version control, and quantum-enhanced model repositories",
    icon: Box,
    category: "management",
    status: "online",
    users: "1.7k",
    gradient: "from-rose-500 to-pink-600",
    bgGradient: "from-rose-50 to-pink-50",
    darkBgGradient: "from-rose-950/20 to-pink-950/20",
    badge: "Personal",
    badgeColor: "bg-rose-500"
  },

  // Getting Started
  {
    id: "introduction",
    href: "/deep-learning/introduction",
    title: "Getting Started",
    description: "Comprehensive platform introduction, tutorials, and quantum deep learning fundamentals",
    icon: BookOpen,
    category: "docs",
    status: "online",
    users: "3.2k",
    gradient: "from-indigo-500 to-purple-600",
    bgGradient: "from-indigo-50 to-purple-50",
    darkBgGradient: "from-indigo-950/20 to-purple-950/20",
    badge: "Guide",
    badgeColor: "bg-indigo-500"
  }
];

const categories = [
  { id: "all", name: "All Apps", icon: Grid },
  { id: "core", name: "Core Platform", icon: Zap },
  { id: "ai", name: "AI & Intelligence", icon: Brain },
  { id: "quantum", name: "Quantum Computing", icon: Atom },
  { id: "visualization", name: "Visualization", icon: Eye },
  { id: "infrastructure", name: "Infrastructure", icon: Server },
  { id: "management", name: "Management", icon: Settings },
  { id: "analytics", name: "Analytics", icon: BarChart3 },
  { id: "advanced", name: "Advanced Tools", icon: Wand2 },
  { id: "design", name: "Design Tools", icon: Layers },
  { id: "docs", name: "Documentation", icon: BookOpen }
];

export default function QuantumWeaverDashboard() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [favoriteApps, setFavoriteApps] = useState<string[]>([]);

  // Filter apps based on search and category
  const filteredApps = platformApps.filter(app => {
    const matchesSearch = app.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         app.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === "all" || app.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  // Load favorites from localStorage
  useEffect(() => {
    const saved = localStorage.getItem('qw-favorites');
    if (saved) {
      setFavoriteApps(JSON.parse(saved));
    }
  }, []);

  // Toggle favorite
  const toggleFavorite = (appId: string) => {
    const newFavorites = favoriteApps.includes(appId)
      ? favoriteApps.filter(id => id !== appId)
      : [...favoriteApps, appId];
    setFavoriteApps(newFavorites);
    localStorage.setItem('qw-favorites', JSON.stringify(newFavorites));
  };

  // Get status color
  const getStatusColor = (status: string) => {
    switch (status) {
      case "online": return "bg-green-500";
      case "beta": return "bg-yellow-500";
      case "offline": return "bg-red-500";
      default: return "bg-gray-500";
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 dark:from-slate-950 dark:via-blue-950 dark:to-indigo-950">
      {/* Animated Background Grid */}
      <div className="absolute inset-0 bg-grid-slate-200/20 dark:bg-grid-slate-800/20 [mask-image:linear-gradient(0deg,white,rgba(255,255,255,0.5))] pointer-events-none" />
      
      <div className="relative z-10 min-h-screen">
        {/* Header */}
        <div className="border-b bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl sticky top-0 z-50">
          <div className="max-w-7xl mx-auto px-6 py-6">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-4">
                <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                  <Zap className="h-7 w-7 text-white" />
                </div>
                <div>
                  <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-900 to-slate-600 dark:from-white dark:to-slate-300 bg-clip-text text-transparent">
                    Quantum Weaver Platform
                  </h1>
                  <p className="text-slate-600 dark:text-slate-400 text-lg">
                    Deep Learning • Quantum Computing • Neural Intelligence
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2 px-4 py-2 bg-green-100 dark:bg-green-900/30 rounded-full">
                  <div className="h-2 w-2 bg-green-500 rounded-full animate-pulse" />
                  <span className="text-sm font-medium text-green-700 dark:text-green-400">
                    All Systems Online
                  </span>
                </div>
                <Badge variant="outline" className="bg-blue-50 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800">
                  {filteredApps.length} Apps Available
                </Badge>
              </div>
            </div>

            {/* Search and Filters */}
            <div className="flex flex-col lg:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
                <Input
                  placeholder="Search applications, features, or tools..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 h-12 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                />
              </div>
              
              <div className="flex items-center gap-3">
                <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                  <SelectTrigger className="w-48 h-12 bg-white dark:bg-slate-800">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.map((category) => (
                      <SelectItem key={category.id} value={category.id}>
                        <div className="flex items-center gap-2">
                          <category.icon className="h-4 w-4" />
                          {category.name}
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>

                <div className="flex items-center border rounded-lg bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700">
                  <Button
                    variant={viewMode === "grid" ? "default" : "ghost"}
                    size="sm"
                    onClick={() => setViewMode("grid")}
                    className="h-12 px-4 rounded-r-none"
                  >
                    <Grid className="h-4 w-4" />
                  </Button>
                  <Button
                    variant={viewMode === "list" ? "default" : "ghost"}
                    size="sm"
                    onClick={() => setViewMode("list")}
                    className="h-12 px-4 rounded-l-none"
                  >
                    <List className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="max-w-7xl mx-auto px-6 py-8">
          {/* Quick Stats */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <Card className="bg-gradient-to-br from-blue-500 to-cyan-600 text-white border-0">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-blue-100 text-sm font-medium">Active Models</p>
                    <p className="text-3xl font-bold">23</p>
                  </div>
                  <Brain className="h-8 w-8 text-blue-200" />
                </div>
              </CardContent>
            </Card>
            
            <Card className="bg-gradient-to-br from-emerald-500 to-teal-600 text-white border-0">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-emerald-100 text-sm font-medium">GPU Utilization</p>
                    <p className="text-3xl font-bold">87%</p>
                  </div>
                  <Monitor className="h-8 w-8 text-emerald-200" />
                </div>
              </CardContent>
            </Card>
            
            <Card className="bg-gradient-to-br from-purple-500 to-violet-600 text-white border-0">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-purple-100 text-sm font-medium">Training Jobs</p>
                    <p className="text-3xl font-bold">156</p>
                  </div>
                  <PlayCircle className="h-8 w-8 text-purple-200" />
                </div>
              </CardContent>
            </Card>
            
            <Card className="bg-gradient-to-br from-orange-500 to-red-600 text-white border-0">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-orange-100 text-sm font-medium">Platform Users</p>
                    <p className="text-3xl font-bold">12.4k</p>
                  </div>
                  <Users className="h-8 w-8 text-orange-200" />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Applications Grid */}
          {viewMode === "grid" ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filteredApps.map((app) => {
                const Icon = app.icon;
                const isFavorite = favoriteApps.includes(app.id);
                
                return (
                  <Card 
                    key={app.id} 
                    className={`group relative overflow-hidden border-0 bg-gradient-to-br ${app.bgGradient} dark:${app.darkBgGradient} hover:shadow-2xl hover:shadow-blue-500/10 transition-all duration-300 hover:scale-105`}
                  >
                    <CardHeader className="pb-2">
                      <div className="flex items-start justify-between">
                        <div className={`h-12 w-12 rounded-xl bg-gradient-to-br ${app.gradient} flex items-center justify-center shadow-lg`}>
                          <Icon className="h-6 w-6 text-white" />
                        </div>
                        <div className="flex items-center gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.preventDefault();
                              toggleFavorite(app.id);
                            }}
                            className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity"
                          >
                            <Heart className={`h-4 w-4 ${isFavorite ? 'fill-red-500 text-red-500' : 'text-slate-400'}`} />
                          </Button>
                          <div className={`h-2 w-2 rounded-full ${getStatusColor(app.status)}`} />
                        </div>
                      </div>
                      
                      <div className="space-y-1">
                        <CardTitle className="text-lg font-semibold text-slate-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
                          {app.title}
                        </CardTitle>
                        <div className="flex items-center gap-2">
                          <Badge className={`${app.badgeColor} text-white text-xs px-2 py-1`}>
                            {app.badge}
                          </Badge>
                          <span className="text-xs text-slate-500 dark:text-slate-400">
                            {app.users} users
                          </span>
                        </div>
                      </div>
                    </CardHeader>
                    
                    <CardContent className="pt-0">
                      <CardDescription className="text-slate-600 dark:text-slate-300 text-sm leading-relaxed mb-4">
                        {app.description}
                      </CardDescription>
                      
                      <Button 
                        asChild 
                        className={`w-full bg-gradient-to-r ${app.gradient} hover:shadow-lg transition-all duration-200`}
                      >
                        <Link href={app.href} className="flex items-center justify-center gap-2">
                          Launch App
                          <ChevronRight className="h-4 w-4" />
                        </Link>
                      </Button>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          ) : (
            // List View
            <div className="space-y-4">
              {filteredApps.map((app) => {
                const Icon = app.icon;
                const isFavorite = favoriteApps.includes(app.id);
                
                return (
                  <Card key={app.id} className="bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:shadow-lg transition-all duration-200">
                    <CardContent className="p-6">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4 flex-1">
                          <div className={`h-12 w-12 rounded-xl bg-gradient-to-br ${app.gradient} flex items-center justify-center`}>
                            <Icon className="h-6 w-6 text-white" />
                          </div>
                          <div className="flex-1">
                            <div className="flex items-center gap-3 mb-1">
                              <h3 className="text-lg font-semibold text-slate-900 dark:text-white">{app.title}</h3>
                              <Badge className={`${app.badgeColor} text-white text-xs`}>{app.badge}</Badge>
                              <div className={`h-2 w-2 rounded-full ${getStatusColor(app.status)}`} />
                            </div>
                            <p className="text-slate-600 dark:text-slate-400 text-sm">{app.description}</p>
                            <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">{app.users} active users</p>
                          </div>
                        </div>
                        <div className="flex items-center gap-3">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => toggleFavorite(app.id)}
                            className="h-8 w-8 p-0"
                          >
                            <Heart className={`h-4 w-4 ${isFavorite ? 'fill-red-500 text-red-500' : 'text-slate-400'}`} />
                          </Button>
                          <Button asChild className={`bg-gradient-to-r ${app.gradient}`}>
                            <Link href={app.href} className="flex items-center gap-2">
                              Launch
                              <ChevronRight className="h-4 w-4" />
                            </Link>
                          </Button>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {/* No Results */}
          {filteredApps.length === 0 && (
            <div className="text-center py-16">
              <div className="h-16 w-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mx-auto mb-4">
                <Search className="h-8 w-8 text-slate-400" />
              </div>
              <h3 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">No applications found</h3>
              <p className="text-slate-600 dark:text-slate-400 mb-4">
                Try adjusting your search terms or category filter
              </p>
              <Button onClick={() => { setSearchTerm(""); setSelectedCategory("all"); }}>
                Clear Filters
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
} 