import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import Layout from "@/components/Layout"; import { Button } from "@/components/ui/button"; import { useAuth } from "@/contexts/AuthContext"; import { aethexToast } from "@/lib/aethex-toast"; import { aethexProjectService, aethexAchievementService, } from "@/lib/aethex-database-adapter"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import LoadingScreen from "@/components/LoadingScreen"; import { Link } from "react-router-dom"; import { User, Settings, Activity, TrendingUp, Zap, Target, Users, Calendar, Bell, Star, Trophy, Rocket, Code, Database, Shield, ChevronRight, MoreHorizontal, Play, Pause, BarChart3, } from "lucide-react"; export default function Dashboard() { const navigate = useNavigate(); const { user, profile, loading: authLoading } = useAuth(); const [isLoading, setIsLoading] = useState(true); const [projects, setProjects] = useState([]); const [achievements, setAchievements] = useState([]); const [stats, setStats] = useState({ activeProjects: 0, completedTasks: 0, teamMembers: 0, performanceScore: "0%", }); useEffect(() => { console.log("Dashboard useEffect:", { user: !!user, profile: !!profile, authLoading }); // Force redirect immediately if no user if (!user) { console.log("No user, redirecting to login"); setIsLoading(false); navigate("/login", { replace: true }); return; } if (user && profile) { console.log("User and profile exist, loading dashboard data"); loadDashboardData(); } else if (user && !profile && !authLoading) { console.log("User exists but no profile, clearing loading"); setIsLoading(false); } }, [user, profile, authLoading, navigate]); const loadDashboardData = async () => { try { setIsLoading(true); // Load user's projects with error handling let userProjects = []; try { userProjects = await aethexProjectService.getUserProjects(user!.id); setProjects(userProjects); } catch (projectError) { console.warn("Could not load projects:", projectError); setProjects([]); } // Load user's achievements with error handling let userAchievements = []; try { userAchievements = await aethexAchievementService.getUserAchievements(user!.id); setAchievements(userAchievements); } catch (achievementError) { console.warn("Could not load achievements:", achievementError); setAchievements([]); } // Calculate stats const activeCount = userProjects.filter( (p) => p.status === "in_progress", ).length; const completedCount = userProjects.filter( (p) => p.status === "completed", ).length; setStats({ activeProjects: activeCount, completedTasks: completedCount, teamMembers: 8, // Mock for now performanceScore: `${Math.min(95, 70 + completedCount * 5)}%`, }); } catch (error) { console.error("Error loading dashboard data:", error); aethexToast.error({ title: "Failed to load dashboard", description: "Please try refreshing the page", }); } finally { setIsLoading(false); } }; const handleQuickAction = async (actionTitle: string) => { switch (actionTitle) { case "Start New Project": navigate("/projects/new"); break; case "Join Team": navigate("/teams"); break; case "Access Labs": navigate("/research"); break; case "View Analytics": aethexToast.info({ title: "Analytics", description: "Analytics dashboard coming soon!", }); break; default: aethexToast.info({ title: actionTitle, description: "Feature coming soon!", }); } }; // Don't show loading screen if no user - just redirect if (!user) { return null; } // Show loading only if we have a user but are still loading data if (authLoading || isLoading) { return ( ); } // Show profile setup if no profile exists, but allow dashboard to continue const showProfileSetup = !profile; const statsDisplay = [ { label: "Active Projects", value: stats.activeProjects, icon: Rocket, color: "from-blue-500 to-purple-600", }, { label: "Completed Tasks", value: 47, icon: Trophy, color: "from-green-500 to-blue-600", }, { label: "Team Members", value: 8, icon: Users, color: "from-purple-500 to-pink-600", }, { label: "Performance Score", value: "94%", icon: TrendingUp, color: "from-orange-500 to-red-600", }, ]; const getProgressPercentage = (project: any) => { switch (project.status) { case "planning": return 20; case "in_progress": return 60; case "completed": return 100; default: return 0; } }; const getPriorityFromTech = (technologies: string[]) => { if ( technologies.some( (tech) => tech.toLowerCase().includes("ai") || tech.toLowerCase().includes("blockchain"), ) ) { return "High"; } return "Medium"; }; const getAchievementIcon = (iconName: string) => { switch (iconName.toLowerCase()) { case "code": return Code; case "users": return Users; case "rocket": return Rocket; case "database": return Database; case "shield": return Shield; case "trophy": return Trophy; default: return Star; } }; const quickActions = [ { title: "Start New Project", icon: Rocket, color: "from-blue-500 to-purple-600", }, { title: "Join Team", icon: Users, color: "from-green-500 to-blue-600" }, { title: "Access Labs", icon: Zap, color: "from-yellow-500 to-orange-600" }, { title: "View Analytics", icon: BarChart3, color: "from-purple-500 to-pink-600", }, ]; if (isLoading) { return ( ); } return (
{/* Profile Setup Banner */} {showProfileSetup && (

Complete Your Profile

Set up your profile to unlock all features

)} {/* Header */}

Welcome back, {profile?.full_name || user.email?.split('@')[0]}

{profile?.role || 'Member'} • Level {profile?.level || 1} • 7 day streak 🔥

{/* Left Sidebar - User Profile */}
{/* Profile Card */}
User Avatar

{profile?.full_name || user.email?.split('@')[0]}

{profile?.role || 'Member'}

Level {profile?.level || 1}
{/* XP Progress */}
XP Progress {profile?.total_xp || 0} / {((profile?.level || 1) * 1000)}
{/* Quick Actions */} Quick Actions {quickActions.map((action, index) => { const Icon = action.icon; return ( ); })}
{/* Main Content */}
{/* Stats Grid */}
{statsDisplay.map((stat, index) => { const Icon = stat.icon; return (

{stat.label}

{stat.value}

); })}
{/* Recent Projects */}
Recent Projects Your active development projects
{projects.length === 0 ? (

No projects yet. Start your first project!

) : ( projects.slice(0, 3).map((project: any, index) => (

{project.title}

{project.status?.replace("_", " ").toUpperCase()} •{" "} {project.technologies?.slice(0, 2).join(", ") || "No tech specified"}

{getProgressPercentage(project)}%

{getPriorityFromTech(project.technologies || [])}
)) )} {/* Achievements */} Achievements Your progress and accomplishments
{achievements.length === 0 ? (

No achievements unlocked yet. Complete projects to earn achievements!

) : ( achievements.map((achievement: any, index) => { const Icon = getAchievementIcon(achievement.icon || 'star'); return (

{achievement.title}

{achievement.description}

{achievement.earned && ( )}
); }) )}
); }