import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { useSport } from "@/hooks/useSport";
import { 
  Brain, 
  Target, 
  CheckCircle, 
  Clock, 
  TrendingUp,
  Users,
  Award,
  AlertTriangle,
  Lightbulb,
  ArrowRight,
  Star,
  Zap,
  Shield,
  BarChart3,
  Settings,
  Play,
  ChevronDown,
  ChevronUp
} from "lucide-react";

interface OnboardingRecommendation {
  id: string;
  title: string;
  description: string;
  priority: "critical" | "high" | "medium" | "low";
  category: "setup" | "management" | "analytics" | "engagement" | "performance" | "compliance";
  estimatedTime: string;
  benefits: string[];
  actionUrl: string;
  completed: boolean;
  aiReasoning: string;
  sportSpecific: boolean;
  urgencyScore: number;
  prerequisites: string[];
  difficulty: "beginner" | "intermediate" | "advanced";
}

interface SportAnalysis {
  sportType: string;
  currentSetup: {
    playersCount: number;
    teamsCount: number;
    coachesCount: number;
    hasPositions: boolean;
    hasRoster: boolean;
    hasBiometrics: boolean;
    hasAttendance: boolean;
  };
  setupScore: number;
  readinessLevel: string;
  nextMilestone: string;
  recommendations: OnboardingRecommendation[];
}

export default function SmartOnboarding() {
  const { toast } = useToast();
  const { user } = useAuth();
  const { selectedSport } = useSport();
  const queryClient = useQueryClient();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [expandedRecommendation, setExpandedRecommendation] = useState<string | null>(null);

  // Fetch smart onboarding data
  const { data: onboardingData, isLoading } = useQuery<SportAnalysis>({
    queryKey: ["/api/smart-onboarding", selectedSport],
    queryFn: async () => {
      if (!selectedSport) throw new Error("No sport selected");
      const response = await fetch(`/api/smart-onboarding?sport=${selectedSport}`);
      if (!response.ok) throw new Error("Failed to fetch onboarding data");
      return response.json();
    },
    enabled: !!selectedSport
  });

  // Complete recommendation mutation
  const completeRecommendationMutation = useMutation({
    mutationFn: async (recommendationId: string) => {
      const response = await fetch(`/api/smart-onboarding/complete`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ recommendationId })
      });
      if (!response.ok) throw new Error("Failed to complete recommendation");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/smart-onboarding"] });
      toast({ title: "Recommendation completed!" });
    }
  });

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "critical": return "bg-red-500";
      case "high": return "bg-orange-500";
      case "medium": return "bg-yellow-500";
      case "low": return "bg-green-500";
      default: return "bg-gray-500";
    }
  };

  const getPriorityIcon = (priority: string) => {
    switch (priority) {
      case "critical": return <AlertTriangle className="h-4 w-4" />;
      case "high": return <Zap className="h-4 w-4" />;
      case "medium": return <Target className="h-4 w-4" />;
      case "low": return <Lightbulb className="h-4 w-4" />;
      default: return <Target className="h-4 w-4" />;
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case "setup": return <Settings className="h-4 w-4" />;
      case "management": return <Users className="h-4 w-4" />;
      case "analytics": return <BarChart3 className="h-4 w-4" />;
      case "performance": return <TrendingUp className="h-4 w-4" />;
      case "compliance": return <Shield className="h-4 w-4" />;
      default: return <Target className="h-4 w-4" />;
    }
  };

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case "beginner": return "bg-green-100 text-green-800";
      case "intermediate": return "bg-yellow-100 text-yellow-800";
      case "advanced": return "bg-red-100 text-red-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const getReadinessColor = (level: string) => {
    if (level.includes("Championship")) return "text-green-600";
    if (level.includes("Competition")) return "text-blue-600";
    if (level.includes("Training")) return "text-purple-600";
    if (level.includes("Building")) return "text-orange-600";
    return "text-gray-600";
  };

  const categories = [
    { value: "all", label: "All Recommendations", icon: Target },
    { value: "setup", label: "Setup", icon: Settings },
    { value: "management", label: "Management", icon: Users },
    { value: "analytics", label: "Analytics", icon: BarChart3 },
    { value: "performance", label: "Performance", icon: TrendingUp },
    { value: "compliance", label: "Compliance", icon: Shield }
  ];

  const filteredRecommendations = selectedCategory === "all" 
    ? onboardingData?.recommendations || []
    : onboardingData?.recommendations?.filter(rec => rec.category === selectedCategory) || [];

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <Brain className="h-12 w-12 animate-pulse text-primary mx-auto mb-4" />
          <p className="text-lg">Analyzing your {selectedSport} setup...</p>
        </div>
      </div>
    );
  }

  if (!selectedSport) {
    return (
      <div className="text-center py-12">
        <Brain className="h-16 w-16 text-gray-400 mx-auto mb-4" />
        <h2 className="text-2xl font-bold text-gray-900 mb-2">Select Your Sport</h2>
        <p className="text-gray-600">Please select a sport to get personalized onboarding recommendations.</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight flex items-center space-x-2">
            <Brain className="h-8 w-8 text-primary" />
            <span>Smart Onboarding</span>
          </h1>
          <p className="text-muted-foreground">
            AI-powered recommendations tailored for your {selectedSport} team
          </p>
        </div>
        <Badge variant="secondary" className="flex items-center space-x-1">
          <Star className="h-3 w-3" />
          <span>AI-Powered</span>
        </Badge>
      </div>

      {/* Overview Dashboard */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Setup Score */}
        <Card className="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200">
          <CardHeader className="pb-3">
            <CardTitle className="text-lg flex items-center space-x-2">
              <BarChart3 className="h-5 w-5 text-blue-600" />
              <span>Setup Score</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-3xl font-bold text-blue-700">
                  {onboardingData?.setupScore || 0}%
                </span>
                <Badge variant="outline" className="border-blue-300 text-blue-700">
                  {onboardingData?.readinessLevel}
                </Badge>
              </div>
              <Progress 
                value={onboardingData?.setupScore || 0} 
                className="h-2"
              />
              <p className="text-sm text-blue-600">
                {onboardingData?.nextMilestone}
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Current Setup */}
        <Card className="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200">
          <CardHeader className="pb-3">
            <CardTitle className="text-lg flex items-center space-x-2">
              <Users className="h-5 w-5 text-green-600" />
              <span>Team Status</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span>Players:</span>
                <span className="font-semibold">{onboardingData?.currentSetup.playersCount || 0}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span>Teams:</span>
                <span className="font-semibold">{onboardingData?.currentSetup.teamsCount || 0}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span>Coaches:</span>
                <span className="font-semibold">{onboardingData?.currentSetup.coachesCount || 0}</span>
              </div>
              <div className="pt-2 space-y-1">
                <div className="flex items-center space-x-2 text-xs">
                  {onboardingData?.currentSetup.hasRoster ? (
                    <CheckCircle className="h-3 w-3 text-green-500" />
                  ) : (
                    <div className="h-3 w-3 rounded-full border-2 border-gray-300" />
                  )}
                  <span>Roster Setup</span>
                </div>
                <div className="flex items-center space-x-2 text-xs">
                  {onboardingData?.currentSetup.hasPositions ? (
                    <CheckCircle className="h-3 w-3 text-green-500" />
                  ) : (
                    <div className="h-3 w-3 rounded-full border-2 border-gray-300" />
                  )}
                  <span>Position Assignments</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Recommendations Summary */}
        <Card className="bg-gradient-to-br from-purple-50 to-violet-50 border-purple-200">
          <CardHeader className="pb-3">
            <CardTitle className="text-lg flex items-center space-x-2">
              <Lightbulb className="h-5 w-5 text-purple-600" />
              <span>Recommendations</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {["critical", "high", "medium", "low"].map((priority) => {
                const count = filteredRecommendations.filter(r => r.priority === priority).length;
                if (count === 0) return null;
                return (
                  <div key={priority} className="flex items-center justify-between text-sm">
                    <div className="flex items-center space-x-2">
                      <div className={`w-2 h-2 rounded-full ${getPriorityColor(priority)}`} />
                      <span className="capitalize">{priority}</span>
                    </div>
                    <span className="font-semibold">{count}</span>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Category Filter */}
      <div className="flex items-center space-x-2 overflow-x-auto pb-2">
        {categories.map((category) => {
          const Icon = category.icon;
          return (
            <Button
              key={category.value}
              size="sm"
              variant={selectedCategory === category.value ? "default" : "outline"}
              onClick={() => setSelectedCategory(category.value)}
              className="whitespace-nowrap flex items-center space-x-2"
            >
              <Icon className="h-4 w-4" />
              <span>{category.label}</span>
            </Button>
          );
        })}
      </div>

      {/* Recommendations List */}
      <div className="space-y-4">
        {filteredRecommendations.length === 0 ? (
          <Card>
            <CardContent className="text-center py-12">
              <CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
              <h3 className="text-xl font-semibold mb-2">All Set!</h3>
              <p className="text-gray-600">
                {selectedCategory === "all" 
                  ? "No recommendations available. Your setup looks great!"
                  : `No ${selectedCategory} recommendations at this time.`
                }
              </p>
            </CardContent>
          </Card>
        ) : (
          filteredRecommendations.map((recommendation) => (
            <Card key={recommendation.id} className="hover:shadow-md transition-shadow">
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center space-x-3 mb-2">
                      <div className={`p-1 rounded ${getPriorityColor(recommendation.priority)} text-white`}>
                        {getPriorityIcon(recommendation.priority)}
                      </div>
                      <div>
                        <CardTitle className="text-lg">{recommendation.title}</CardTitle>
                        <div className="flex items-center space-x-2 mt-1">
                          <Badge variant="outline" className="text-xs">
                            {getCategoryIcon(recommendation.category)}
                            <span className="ml-1 capitalize">{recommendation.category}</span>
                          </Badge>
                          <Badge variant="secondary" className={`text-xs ${getDifficultyColor(recommendation.difficulty)}`}>
                            {recommendation.difficulty}
                          </Badge>
                          {recommendation.sportSpecific && (
                            <Badge variant="outline" className="text-xs text-blue-600 border-blue-300">
                              {selectedSport} Specific
                            </Badge>
                          )}
                        </div>
                      </div>
                    </div>
                    <CardDescription className="text-sm">
                      {recommendation.description}
                    </CardDescription>
                  </div>
                  <div className="flex items-center space-x-2 ml-4">
                    <Badge variant="secondary" className="text-xs flex items-center space-x-1">
                      <Clock className="h-3 w-3" />
                      <span>{recommendation.estimatedTime}</span>
                    </Badge>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => setExpandedRecommendation(
                        expandedRecommendation === recommendation.id ? null : recommendation.id
                      )}
                    >
                      {expandedRecommendation === recommendation.id ? (
                        <ChevronUp className="h-4 w-4" />
                      ) : (
                        <ChevronDown className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                </div>
              </CardHeader>

              {expandedRecommendation === recommendation.id && (
                <CardContent className="pt-0 border-t">
                  <div className="space-y-4">
                    {/* AI Reasoning */}
                    <div className="bg-blue-50 p-3 rounded-lg">
                      <div className="flex items-center space-x-2 mb-2">
                        <Brain className="h-4 w-4 text-blue-600" />
                        <span className="text-sm font-semibold text-blue-900">AI Analysis</span>
                      </div>
                      <p className="text-sm text-blue-800">{recommendation.aiReasoning}</p>
                    </div>

                    {/* Benefits */}
                    <div>
                      <h4 className="text-sm font-semibold mb-2 flex items-center space-x-2">
                        <Star className="h-4 w-4 text-yellow-500" />
                        <span>Benefits</span>
                      </h4>
                      <ul className="space-y-1">
                        {recommendation.benefits.map((benefit, index) => (
                          <li key={index} className="text-sm text-gray-600 flex items-center space-x-2">
                            <CheckCircle className="h-3 w-3 text-green-500" />
                            <span>{benefit}</span>
                          </li>
                        ))}
                      </ul>
                    </div>

                    {/* Prerequisites */}
                    {recommendation.prerequisites.length > 0 && (
                      <div>
                        <h4 className="text-sm font-semibold mb-2">Prerequisites</h4>
                        <div className="flex flex-wrap gap-1">
                          {recommendation.prerequisites.map((prereq, index) => (
                            <Badge key={index} variant="outline" className="text-xs">
                              {prereq}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Action Button */}
                    <div className="flex items-center justify-between pt-2">
                      <div className="flex items-center space-x-2 text-sm text-gray-500">
                        <Target className="h-4 w-4" />
                        <span>Urgency Score: {recommendation.urgencyScore}/100</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => completeRecommendationMutation.mutate(recommendation.id)}
                          disabled={completeRecommendationMutation.isPending}
                        >
                          <CheckCircle className="h-4 w-4 mr-2" />
                          Mark Complete
                        </Button>
                        <Button size="sm" asChild>
                          <a href={recommendation.actionUrl} className="flex items-center space-x-2">
                            <Play className="h-4 w-4" />
                            <span>Get Started</span>
                            <ArrowRight className="h-4 w-4" />
                          </a>
                        </Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              )}
            </Card>
          ))
        )}
      </div>
    </div>
  );
}