import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Sparkles, Clock, Target, Users, Trophy, BarChart3, 
  CheckCircle, ArrowRight, Zap, Brain, TrendingUp, 
  Calendar, Award, UserPlus, Activity, Star
} from "lucide-react";
import { useSport } from "@/hooks/useSport";
import { useLocation } from "wouter";

interface SmartRecommendation {
  id: string;
  title: string;
  description: string;
  priority: "high" | "medium" | "low";
  complexity: number; // 1-5 scale
  estimatedTime: string;
  category: "setup" | "management" | "analytics" | "engagement";
  sportSpecific: boolean;
  prerequisites: string[];
  benefits: string[];
  icon: React.ReactNode;
  route?: string;
  completed?: boolean;
}

interface SportProfile {
  name: string;
  type: "team" | "individual";
  complexity: number;
  keyFeatures: string[];
  recommendations: SmartRecommendation[];
  setupPriority: string[];
}

export default function SmartOnboardingEngine() {
  const [, setLocation] = useLocation();
  const { currentSport, sportName, isTeamSport } = useSport();
  const [selectedRecommendation, setSelectedRecommendation] = useState<SmartRecommendation | null>(null);
  const [completedRecommendations, setCompletedRecommendations] = useState<string[]>([]);

  const { data: onboardingProgress } = useQuery({
    queryKey: ["/api/onboarding/progress"],
  });

  const { data: smartRecommendations, refetch: refetchRecommendations } = useQuery({
    queryKey: ["/api/onboarding/smart-recommendations", currentSport],
  });

  // Helper functions for mapping recommendation data
  const getRecommendationTitle = (id: string): string => {
    const titles: Record<string, string> = {
      "team-setup": "Create Your First Team",
      "player-registration": "Register Players",
      "coach-assignment": "Assign Coaches",
      "roster-management": "Set Up Roster System",
      "attendance-tracking": "Enable Attendance Tracking",
      "analytics-setup": "Configure Analytics Dashboard",
      "biometric-integration": "Biometric Player ID"
    };
    return titles[id] || id;
  };

  const getRecommendationDescription = (id: string): string => {
    const descriptions: Record<string, string> = {
      "team-setup": `Set up your ${sportName} team with logo, colors, and basic information`,
      "player-registration": `Add ${sportName} players with profiles, positions, and contact details`,
      "coach-assignment": `Add coaching staff and define their roles for ${sportName}`,
      "roster-management": `Configure ${sportName} positions and lineup management`,
      "attendance-tracking": "Monitor player attendance for training and matches",
      "analytics-setup": `Set up performance analytics for ${sportName} insights`,
      "biometric-integration": "Set up fingerprint scanning for secure player identification"
    };
    return descriptions[id] || "";
  };

  const getRecommendationIcon = (id: string): React.ReactNode => {
    const icons: Record<string, React.ReactNode> = {
      "team-setup": <Trophy className="h-5 w-5 text-yellow-600" />,
      "player-registration": <UserPlus className="h-5 w-5 text-green-600" />,
      "coach-assignment": <Award className="h-5 w-5 text-purple-600" />,
      "roster-management": <Users className="h-5 w-5 text-blue-600" />,
      "attendance-tracking": <Calendar className="h-5 w-5 text-orange-600" />,
      "analytics-setup": <BarChart3 className="h-5 w-5 text-cyan-600" />,
      "biometric-integration": <Activity className="h-5 w-5 text-red-600" />
    };
    return icons[id] || <CheckCircle className="h-5 w-5" />;
  };

  const getRecommendationRoute = (id: string): string => {
    const routes: Record<string, string> = {
      "team-setup": "/teams",
      "player-registration": "/players/register",
      "coach-assignment": "/coaches",
      "roster-management": "/roster",
      "attendance-tracking": "/attendance",
      "analytics-setup": "/analytics",
      "biometric-integration": "/biometric"
    };
    return routes[id] || "/";
  };

  const getRecommendationBenefits = (id: string): string[] => {
    const benefits: Record<string, string[]> = {
      "team-setup": ["Organize players effectively", "Professional team presentation", "Team identity"],
      "player-registration": ["Complete player database", "Contact management", "Performance tracking"],
      "coach-assignment": ["Clear coaching structure", "Role definition", "Team leadership"],
      "roster-management": ["Strategic lineup planning", "Position optimization", "Match preparation"],
      "attendance-tracking": ["Attendance insights", "Automated notifications", "Performance correlation"],
      "analytics-setup": ["Performance insights", "Data-driven decisions", "Progress tracking"],
      "biometric-integration": ["Secure identification", "Fraud prevention", "Quick check-in"]
    };
    return benefits[id] || [];
  };

  const getRecommendationPrerequisites = (id: string): string[] => {
    const prerequisites: Record<string, string[]> = {
      "team-setup": [],
      "player-registration": ["team-setup"],
      "coach-assignment": ["team-setup"],
      "roster-management": ["team-setup", "player-registration"],
      "attendance-tracking": ["player-registration"],
      "analytics-setup": ["player-registration", "team-setup"],
      "biometric-integration": ["player-registration"]
    };
    return prerequisites[id] || [];
  };

  // Use real data from API or fallback to local recommendations
  const getSportProfile = (): SportProfile => {
    // If we have API data, use it to override local recommendations
    if (smartRecommendations && smartRecommendations.recommendations) {
      const apiRecommendations = smartRecommendations.recommendations.map((rec: any) => ({
        id: rec.id,
        title: getRecommendationTitle(rec.id),
        description: getRecommendationDescription(rec.id),
        priority: rec.priority,
        complexity: rec.complexity,
        estimatedTime: rec.estimatedTime,
        category: rec.category,
        sportSpecific: rec.id.includes('team') || rec.id.includes('coach') || rec.id.includes('roster'),
        prerequisites: getRecommendationPrerequisites(rec.id),
        benefits: getRecommendationBenefits(rec.id),
        icon: getRecommendationIcon(rec.id),
        route: getRecommendationRoute(rec.id),
        completed: rec.completed
      }));

      return {
        name: sportName,
        type: smartRecommendations.isTeamSport ? "team" : "individual",
        complexity: smartRecommendations.isTeamSport ? 4 : 2,
        keyFeatures: smartRecommendations.isTeamSport 
          ? ["Team Management", "Roster Planning", "Coach Assignment", "Formation Setup"]
          : ["Individual Tracking", "Personal Records", "Goal Setting", "Progress Monitoring"],
        recommendations: apiRecommendations,
        setupPriority: smartRecommendations.isTeamSport 
          ? ["team-setup", "player-registration", "coach-assignment", "roster-management"]
          : ["player-registration", "analytics-setup", "attendance-tracking"]
      };
    }

    // Fallback to local sport-specific recommendations
    const baseRecommendations: SmartRecommendation[] = [
      {
        id: "team-setup",
        title: "Create Your First Team",
        description: `Set up your ${sportName} team with logo, colors, and basic information`,
        priority: "high",
        complexity: 2,
        estimatedTime: "5 min",
        category: "setup",
        sportSpecific: true,
        prerequisites: [],
        benefits: ["Organize players effectively", "Professional team presentation", "Team identity"],
        icon: <Trophy className="h-5 w-5 text-yellow-600" />,
        route: "/teams"
      },
      {
        id: "player-registration",
        title: "Register Players",
        description: `Add ${sportName} players with profiles, positions, and contact details`,
        priority: "high",
        complexity: 2,
        estimatedTime: "3 min per player",
        category: "setup",
        sportSpecific: true,
        prerequisites: ["team-setup"],
        benefits: ["Complete player database", "Contact management", "Performance tracking"],
        icon: <UserPlus className="h-5 w-5 text-green-600" />,
        route: "/players/register"
      }
    ];

    if (isTeamSport) {
      baseRecommendations.push(
        {
          id: "roster-management",
          title: "Set Up Roster System",
          description: `Configure ${sportName} positions and lineup management`,
          priority: "medium",
          complexity: 3,
          estimatedTime: "10 min",
          category: "management",
          sportSpecific: true,
          prerequisites: ["team-setup", "player-registration"],
          benefits: ["Strategic lineup planning", "Position optimization", "Match preparation"],
          icon: <Users className="h-5 w-5 text-blue-600" />,
          route: "/roster"
        },
        {
          id: "coach-assignment",
          title: "Assign Coaches",
          description: `Add coaching staff and define their roles for ${sportName}`,
          priority: "medium",
          complexity: 2,
          estimatedTime: "5 min",
          category: "setup",
          sportSpecific: true,
          prerequisites: ["team-setup"],
          benefits: ["Clear coaching structure", "Role definition", "Team leadership"],
          icon: <Award className="h-5 w-5 text-purple-600" />,
          route: "/coaches"
        }
      );
    }

    // Add universal recommendations
    baseRecommendations.push(
      {
        id: "attendance-tracking",
        title: "Enable Attendance Tracking",
        description: "Monitor player attendance for training and matches",
        priority: "medium",
        complexity: 2,
        estimatedTime: "5 min",
        category: "management",
        sportSpecific: false,
        prerequisites: ["player-registration"],
        benefits: ["Attendance insights", "Automated notifications", "Performance correlation"],
        icon: <Calendar className="h-5 w-5 text-orange-600" />,
        route: "/attendance"
      },
      {
        id: "analytics-setup",
        title: "Configure Analytics Dashboard",
        description: `Set up performance analytics for ${sportName} insights`,
        priority: "low",
        complexity: 3,
        estimatedTime: "8 min",
        category: "analytics",
        sportSpecific: true,
        prerequisites: ["player-registration", "team-setup"],
        benefits: ["Performance insights", "Data-driven decisions", "Progress tracking"],
        icon: <BarChart3 className="h-5 w-5 text-cyan-600" />,
        route: "/analytics"
      },
      {
        id: "biometric-integration",
        title: "Biometric Player ID",
        description: "Set up fingerprint scanning for secure player identification",
        priority: "low",
        complexity: 4,
        estimatedTime: "15 min",
        category: "setup",
        sportSpecific: false,
        prerequisites: ["player-registration"],
        benefits: ["Secure identification", "Fraud prevention", "Quick check-in"],
        icon: <Activity className="h-5 w-5 text-red-600" />,
        route: "/biometric"
      }
    );

    return {
      name: sportName,
      type: isTeamSport ? "team" : "individual",
      complexity: isTeamSport ? 4 : 2,
      keyFeatures: isTeamSport 
        ? ["Team Management", "Roster Planning", "Coach Assignment", "Formation Setup"]
        : ["Individual Tracking", "Personal Records", "Goal Setting", "Progress Monitoring"],
      recommendations: baseRecommendations,
      setupPriority: isTeamSport 
        ? ["team-setup", "player-registration", "coach-assignment", "roster-management"]
        : ["player-registration", "analytics-setup", "attendance-tracking"]
    };
  };

  const sportProfile = getSportProfile();

  // Calculate completion percentage - use API data if available
  const totalRecommendations = smartRecommendations?.totalCount || sportProfile.recommendations.length;
  const completedCount = smartRecommendations?.completedCount || completedRecommendations.length;
  const completionPercentage = smartRecommendations?.completionPercentage || (completedCount / totalRecommendations) * 100;

  // Get prioritized recommendations
  const getPrioritizedRecommendations = () => {
    return sportProfile.recommendations
      .map(rec => ({
        ...rec,
        completed: completedRecommendations.includes(rec.id)
      }))
      .sort((a, b) => {
        // Completed items go to bottom
        if (a.completed !== b.completed) return a.completed ? 1 : -1;
        
        // Sort by priority
        const priorityOrder = { high: 3, medium: 2, low: 1 };
        if (priorityOrder[a.priority] !== priorityOrder[b.priority]) {
          return priorityOrder[b.priority] - priorityOrder[a.priority];
        }
        
        // Sort by complexity (easier first)
        return a.complexity - b.complexity;
      });
  };

  const getRecommendationsByCategory = (category: string) => {
    return getPrioritizedRecommendations().filter(rec => rec.category === category);
  };

  const executeRecommendation = (recommendation: SmartRecommendation) => {
    if (recommendation.route) {
      setLocation(recommendation.route);
    }
    
    // Mark as completed (in real app, this would be tracked server-side)
    setCompletedRecommendations(prev => [...prev, recommendation.id]);
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "high": return "bg-red-100 text-red-800 border-red-200";
      case "medium": return "bg-yellow-100 text-yellow-800 border-yellow-200";
      case "low": return "bg-green-100 text-green-800 border-green-200";
      default: return "bg-gray-100 text-gray-800 border-gray-200";
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case "setup": return <Target className="h-4 w-4" />;
      case "management": return <Users className="h-4 w-4" />;
      case "analytics": return <BarChart3 className="h-4 w-4" />;
      case "engagement": return <Zap className="h-4 w-4" />;
      default: return <CheckCircle className="h-4 w-4" />;
    }
  };

  return (
    <div className="space-y-6">
      {/* Sport Analysis Header */}
      <Card className="bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="bg-purple-100 p-2 rounded-lg">
                <Brain className="h-6 w-6 text-purple-600" />
              </div>
              <div>
                <CardTitle className="flex items-center space-x-2">
                  <span>Smart Analysis for {sportName}</span>
                  <Badge variant="secondary" className="bg-purple-100 text-purple-800">
                    <Sparkles className="h-3 w-3 mr-1" />
                    AI-Powered
                  </Badge>
                </CardTitle>
                <CardDescription>
                  Personalized recommendations based on your sport type and goals
                </CardDescription>
              </div>
            </div>
            <div className="text-right">
              <div className="text-2xl font-bold text-purple-600">{Math.round(completionPercentage)}%</div>
              <div className="text-xs text-gray-500">Complete</div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <Progress value={completionPercentage} className="h-2" />
            
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-lg font-semibold text-gray-900">{sportProfile.type}</div>
                <div className="text-xs text-gray-500">Sport Type</div>
              </div>
              <div className="text-center">
                <div className="text-lg font-semibold text-gray-900">{sportProfile.complexity}/5</div>
                <div className="text-xs text-gray-500">Complexity</div>
              </div>
              <div className="text-center">
                <div className="text-lg font-semibold text-gray-900">{sportProfile.recommendations.length}</div>
                <div className="text-xs text-gray-500">Recommendations</div>
              </div>
              <div className="text-center">
                <div className="text-lg font-semibold text-gray-900">
                  {sportProfile.recommendations.filter(r => r.priority === "high").length}
                </div>
                <div className="text-xs text-gray-500">High Priority</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Recommendations Tabs */}
      <Tabs defaultValue="all" className="w-full">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="all">All</TabsTrigger>
          <TabsTrigger value="setup">Setup</TabsTrigger>
          <TabsTrigger value="management">Management</TabsTrigger>
          <TabsTrigger value="analytics">Analytics</TabsTrigger>
          <TabsTrigger value="engagement">Engagement</TabsTrigger>
        </TabsList>

        <TabsContent value="all" className="space-y-4">
          <div className="grid gap-4">
            {getPrioritizedRecommendations().map((recommendation) => (
              <Card 
                key={recommendation.id} 
                className={`transition-all hover:shadow-md ${
                  recommendation.completed ? 'bg-gray-50 opacity-75' : ''
                }`}
              >
                <CardContent className="p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start space-x-4 flex-1">
                      <div className="bg-white p-2 rounded-lg border shadow-sm">
                        {recommendation.icon}
                      </div>
                      
                      <div className="flex-1 space-y-2">
                        <div className="flex items-center space-x-2">
                          <h3 className="font-semibold text-gray-900">{recommendation.title}</h3>
                          <Badge 
                            variant="outline" 
                            className={getPriorityColor(recommendation.priority)}
                          >
                            {recommendation.priority}
                          </Badge>
                          {recommendation.sportSpecific && (
                            <Badge variant="secondary" className="bg-blue-100 text-blue-800">
                              {sportName}
                            </Badge>
                          )}
                          {recommendation.completed && (
                            <Badge variant="secondary" className="bg-green-100 text-green-800">
                              <CheckCircle className="h-3 w-3 mr-1" />
                              Complete
                            </Badge>
                          )}
                        </div>
                        
                        <p className="text-gray-600 text-sm">{recommendation.description}</p>
                        
                        <div className="flex items-center space-x-4 text-xs text-gray-500">
                          <div className="flex items-center space-x-1">
                            <Clock className="h-3 w-3" />
                            <span>{recommendation.estimatedTime}</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <TrendingUp className="h-3 w-3" />
                            <span>Level {recommendation.complexity}</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            {getCategoryIcon(recommendation.category)}
                            <span className="capitalize">{recommendation.category}</span>
                          </div>
                        </div>

                        {recommendation.benefits.length > 0 && (
                          <div className="space-y-1">
                            <div className="text-xs font-medium text-gray-700">Benefits:</div>
                            <div className="flex flex-wrap gap-1">
                              {recommendation.benefits.slice(0, 3).map((benefit, index) => (
                                <Badge key={index} variant="secondary" className="text-xs">
                                  {benefit}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex flex-col space-y-2">
                      <Button
                        size="sm"
                        onClick={() => executeRecommendation(recommendation)}
                        disabled={recommendation.completed}
                        className="whitespace-nowrap"
                      >
                        {recommendation.completed ? (
                          <>
                            <CheckCircle className="h-4 w-4 mr-2" />
                            Done
                          </>
                        ) : (
                          <>
                            Start
                            <ArrowRight className="h-4 w-4 ml-2" />
                          </>
                        )}
                      </Button>
                      
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setSelectedRecommendation(recommendation)}
                      >
                        Details
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="setup" className="space-y-4">
          <div className="grid gap-4">
            {getRecommendationsByCategory("setup").map((recommendation) => (
              <Card key={recommendation.id} className="transition-all hover:shadow-md">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      {recommendation.icon}
                      <div>
                        <h3 className="font-semibold">{recommendation.title}</h3>
                        <p className="text-sm text-gray-600">{recommendation.description}</p>
                      </div>
                    </div>
                    <Button size="sm" onClick={() => executeRecommendation(recommendation)}>
                      Start
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="management" className="space-y-4">
          <div className="grid gap-4">
            {getRecommendationsByCategory("management").map((recommendation) => (
              <Card key={recommendation.id} className="transition-all hover:shadow-md">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      {recommendation.icon}
                      <div>
                        <h3 className="font-semibold">{recommendation.title}</h3>
                        <p className="text-sm text-gray-600">{recommendation.description}</p>
                      </div>
                    </div>
                    <Button size="sm" onClick={() => executeRecommendation(recommendation)}>
                      Start
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="analytics" className="space-y-4">
          <div className="grid gap-4">
            {getRecommendationsByCategory("analytics").map((recommendation) => (
              <Card key={recommendation.id} className="transition-all hover:shadow-md">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      {recommendation.icon}
                      <div>
                        <h3 className="font-semibold">{recommendation.title}</h3>
                        <p className="text-sm text-gray-600">{recommendation.description}</p>
                      </div>
                    </div>
                    <Button size="sm" onClick={() => executeRecommendation(recommendation)}>
                      Start
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="engagement" className="space-y-4">
          <div className="grid gap-4">
            {getRecommendationsByCategory("engagement").map((recommendation) => (
              <Card key={recommendation.id} className="transition-all hover:shadow-md">
                <CardContent className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      {recommendation.icon}
                      <div>
                        <h3 className="font-semibold">{recommendation.title}</h3>
                        <p className="text-sm text-gray-600">{recommendation.description}</p>
                      </div>
                    </div>
                    <Button size="sm" onClick={() => executeRecommendation(recommendation)}>
                      Start
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}