import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } 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, Eye,
  Lightbulb, PlayCircle, Shield, AlertTriangle
} from "lucide-react";
import { useSport } from "@/hooks/useSport";
import { useLocation } from "wouter";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

interface SmartRecommendation {
  id: string;
  title: string;
  description: string;
  priority: "critical" | "high" | "medium" | "low";
  complexity: number;
  estimatedTime: string;
  category: "setup" | "management" | "analytics" | "engagement" | "performance" | "compliance";
  sportSpecific: boolean;
  benefits: string[];
  prerequisites: string[];
  route: string;
  completed: boolean;
  aiReasoning: string;
  sportContext: string;
  urgencyScore: number;
}

interface SmartRecommendationResponse {
  recommendations: SmartRecommendation[];
  totalCount: number;
  completedCount: number;
  completionPercentage: number;
  sportType: string;
  isTeamSport: boolean;
  currentSetupScore: number;
  readinessLevel: string;
  aiInsights: string[];
  nextMilestone: string;
  nextPriorityAction: string | null;
}

export default function EnhancedSmartEngine() {
  const [, setLocation] = useLocation();
  const { currentSport, sportName, isTeamSport } = useSport();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [showDetails, setShowDetails] = useState<string | null>(null);

  const { data: smartRecommendations, isLoading, error } = useQuery<SmartRecommendationResponse>({
    queryKey: ["/api/onboarding/smart-recommendations", currentSport],
  });

  const completeRecommendationMutation = useMutation({
    mutationFn: async (recommendationId: string) => {
      return await apiRequest("POST", "/api/onboarding/complete-recommendation", {
        recommendationId,
        timestamp: new Date().toISOString()
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/onboarding/smart-recommendations"] });
      toast({
        title: "Progress Updated",
        description: "Recommendation marked as completed",
      });
    },
  });

  const getPriorityIcon = (priority: string) => {
    switch (priority) {
      case "critical": return <AlertTriangle className="h-4 w-4 text-red-600" />;
      case "high": return <TrendingUp className="h-4 w-4 text-orange-600" />;
      case "medium": return <Target className="h-4 w-4 text-blue-600" />;
      case "low": return <Clock className="h-4 w-4 text-gray-600" />;
      default: return <Target className="h-4 w-4 text-blue-600" />;
    }
  };

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

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case "setup": return <Trophy 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 <Activity className="h-4 w-4" />;
      case "performance": return <Award className="h-4 w-4" />;
      case "compliance": return <Shield className="h-4 w-4" />;
      default: return <Target className="h-4 w-4" />;
    }
  };

  const getComplexityStars = (complexity: number) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star 
        key={i} 
        className={`h-3 w-3 ${i < complexity ? 'text-yellow-500 fill-yellow-500' : 'text-gray-300'}`} 
      />
    ));
  };

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

  const categories = [
    { id: "all", label: "All Recommendations", icon: <Sparkles className="h-4 w-4" /> },
    { id: "setup", label: "Setup", icon: <Trophy className="h-4 w-4" /> },
    { id: "management", label: "Management", icon: <Users className="h-4 w-4" /> },
    { id: "analytics", label: "Analytics", icon: <BarChart3 className="h-4 w-4" /> },
    { id: "engagement", label: "Engagement", icon: <Activity className="h-4 w-4" /> },
    { id: "performance", label: "Performance", icon: <Award className="h-4 w-4" /> },
    { id: "compliance", label: "Compliance", icon: <Shield className="h-4 w-4" /> }
  ];

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-center p-8">
          <div className="flex items-center space-x-2">
            <Brain className="h-6 w-6 text-purple-600 animate-pulse" />
            <span className="text-lg font-medium text-gray-700">Analyzing your {sportName} setup...</span>
          </div>
        </div>
        <div className="grid gap-4">
          {[1, 2, 3].map(i => (
            <div key={i} className="animate-pulse">
              <div className="h-24 bg-gray-200 rounded-lg"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <Card className="border-red-200 bg-red-50">
        <CardContent className="p-6">
          <div className="flex items-center space-x-2">
            <AlertTriangle className="h-5 w-5 text-red-600" />
            <span className="text-red-800">Unable to load smart recommendations</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* AI Analysis Summary */}
      {smartRecommendations && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="bg-gradient-to-br from-purple-50 to-blue-50 border-purple-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-purple-600 font-medium">Setup Score</p>
                  <p className="text-2xl font-bold text-purple-900">{smartRecommendations.currentSetupScore}/100</p>
                </div>
                <Brain className="h-8 w-8 text-purple-600" />
              </div>
              <Progress value={smartRecommendations.currentSetupScore} className="mt-2" />
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-green-600 font-medium">Readiness Level</p>
                  <p className="text-lg font-bold text-green-900">{smartRecommendations.readinessLevel}</p>
                </div>
                <Trophy className="h-8 w-8 text-green-600" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-br from-orange-50 to-yellow-50 border-orange-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-orange-600 font-medium">Next Milestone</p>
                  <p className="text-sm font-medium text-orange-900">{smartRecommendations.nextMilestone}</p>
                </div>
                <Target className="h-8 w-8 text-orange-600" />
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* AI Insights */}
      {smartRecommendations?.aiInsights && smartRecommendations.aiInsights.length > 0 && (
        <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Lightbulb className="h-5 w-5 text-blue-600" />
              <span>AI Insights for {smartRecommendations.sportType}</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {smartRecommendations.aiInsights.map((insight, index) => (
                <div key={index} className="flex items-start space-x-2">
                  <div className="w-2 h-2 bg-blue-500 rounded-full mt-2 flex-shrink-0"></div>
                  <p className="text-sm text-blue-800">{insight}</p>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Category Filters */}
      <div className="flex flex-wrap gap-2">
        {categories.map(category => {
          const count = category.id === "all" 
            ? smartRecommendations?.recommendations?.length || 0
            : smartRecommendations?.recommendations?.filter(r => r.category === category.id).length || 0;
          
          return (
            <Button
              key={category.id}
              variant={selectedCategory === category.id ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedCategory(category.id)}
              className="flex items-center space-x-2"
            >
              {category.icon}
              <span>{category.label}</span>
              <Badge variant="secondary" className="ml-1">{count}</Badge>
            </Button>
          );
        })}
      </div>

      {/* Recommendations List */}
      <div className="space-y-4">
        {filteredRecommendations.map((recommendation, index) => (
          <Card 
            key={recommendation.id} 
            className={`transition-all duration-200 hover:shadow-lg ${
              recommendation.completed ? 'bg-green-50 border-green-200' : 'hover:border-primary'
            }`}
          >
            <CardContent className="p-6">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center space-x-3 mb-3">
                    {getCategoryIcon(recommendation.category)}
                    <h3 className="text-lg font-semibold text-gray-900">{recommendation.title}</h3>
                    <Badge className={`${getPriorityColor(recommendation.priority)} border`}>
                      <div className="flex items-center space-x-1">
                        {getPriorityIcon(recommendation.priority)}
                        <span className="capitalize">{recommendation.priority}</span>
                      </div>
                    </Badge>
                    {recommendation.sportSpecific && (
                      <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
                        {sportName} Specific
                      </Badge>
                    )}
                  </div>

                  <p className="text-gray-600 mb-4">{recommendation.description}</p>

                  <div className="flex items-center space-x-6 text-sm text-gray-500 mb-4">
                    <div className="flex items-center space-x-1">
                      <Clock className="h-4 w-4" />
                      <span>{recommendation.estimatedTime}</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <span>Complexity:</span>
                      <div className="flex space-x-0.5">
                        {getComplexityStars(recommendation.complexity)}
                      </div>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Zap className="h-4 w-4" />
                      <span>Score: {recommendation.urgencyScore}</span>
                    </div>
                  </div>

                  {/* Benefits */}
                  <div className="flex flex-wrap gap-2 mb-4">
                    {recommendation.benefits.slice(0, 3).map((benefit, idx) => (
                      <Badge key={idx} variant="secondary" className="text-xs">
                        {benefit}
                      </Badge>
                    ))}
                    {recommendation.benefits.length > 3 && (
                      <Badge variant="secondary" className="text-xs">
                        +{recommendation.benefits.length - 3} more
                      </Badge>
                    )}
                  </div>

                  {/* AI Reasoning Toggle */}
                  {recommendation.aiReasoning && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setShowDetails(showDetails === recommendation.id ? null : recommendation.id)}
                      className="text-purple-600 hover:text-purple-700 p-0 h-auto"
                    >
                      <Brain className="h-4 w-4 mr-1" />
                      {showDetails === recommendation.id ? 'Hide' : 'Show'} AI Analysis
                    </Button>
                  )}

                  {/* AI Analysis Details */}
                  {showDetails === recommendation.id && (
                    <div className="mt-4 p-4 bg-purple-50 border border-purple-200 rounded-lg">
                      <div className="space-y-2">
                        <div>
                          <p className="text-sm font-medium text-purple-900">AI Reasoning:</p>
                          <p className="text-sm text-purple-800">{recommendation.aiReasoning}</p>
                        </div>
                        <div>
                          <p className="text-sm font-medium text-purple-900">Sport Context:</p>
                          <p className="text-sm text-purple-800">{recommendation.sportContext}</p>
                        </div>
                        {recommendation.prerequisites.length > 0 && (
                          <div>
                            <p className="text-sm font-medium text-purple-900">Prerequisites:</p>
                            <ul className="text-sm text-purple-800 list-disc list-inside">
                              {recommendation.prerequisites.map((prereq, idx) => (
                                <li key={idx}>{prereq}</li>
                              ))}
                            </ul>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex flex-col items-end space-y-2 ml-4">
                  {recommendation.completed ? (
                    <Badge className="bg-green-100 text-green-800 border-green-200">
                      <CheckCircle className="h-3 w-3 mr-1" />
                      Completed
                    </Badge>
                  ) : (
                    <div className="space-y-2">
                      <Button
                        onClick={() => setLocation(recommendation.route)}
                        className="bg-primary hover:bg-primary/90"
                      >
                        Start Now
                        <ArrowRight className="h-4 w-4 ml-1" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => completeRecommendationMutation.mutate(recommendation.id)}
                        disabled={completeRecommendationMutation.isPending}
                      >
                        Mark Complete
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredRecommendations.length === 0 && !isLoading && (
        <Card>
          <CardContent className="p-8 text-center">
            <Trophy className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {selectedCategory === "all" ? "No recommendations available" : `No ${selectedCategory} recommendations`}
            </h3>
            <p className="text-gray-600">
              {selectedCategory === "all" 
                ? "Your setup appears to be complete!" 
                : `No ${selectedCategory} improvements needed at this time.`}
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}