import { useState } from "react";
import { useLocation } from "wouter";
import { 
  BookOpen, 
  GraduationCap, 
  X, 
  Play, 
  CheckCircle2, 
  Circle,
  Zap,
  Users,
  UserPlus,
  Settings,
  BarChart3,
  Shield,
  Trophy
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { useOnboarding, ONBOARDING_TOURS } from "@/components/onboarding/onboarding-provider";
import { Separator } from "@/components/ui/separator";

interface TutorialLauncherProps {
  className?: string;
}

interface TutorialItem {
  id: string;
  title: string;
  description: string;
  icon: any;
  duration: string;
  category: string;
  tourType: string;
  difficulty: 'beginner' | 'intermediate' | 'advanced';
}

const tutorials: TutorialItem[] = [
  {
    id: "dashboard-tour",
    title: "Platform Overview",
    description: "Get familiar with the dashboard and main navigation",
    icon: Zap,
    duration: "2 min",
    category: "Getting Started",
    tourType: "dashboard",
    difficulty: "beginner"
  },
  {
    id: "team-management-tour",
    title: "Managing Teams",
    description: "Learn how to create and manage your teams",
    icon: Users,
    duration: "3 min",
    category: "Core Features",
    tourType: "teamManagement",
    difficulty: "beginner"
  },
  {
    id: "player-registration-tour",
    title: "Player Registration",
    description: "Add and manage player profiles effectively",
    icon: UserPlus,
    duration: "3 min",
    category: "Core Features",
    tourType: "playerRegistration",
    difficulty: "beginner"
  },
  {
    id: "settings-tour",
    title: "Settings & Customization",
    description: "Personalize your experience and manage preferences",
    icon: Settings,
    duration: "2 min",
    category: "Customization",
    tourType: "settingsTour",
    difficulty: "intermediate"
  },
  {
    id: "reports-tour",
    title: "Reports & Analytics",
    description: "Generate insights and track performance metrics",
    icon: BarChart3,
    duration: "4 min",
    category: "Advanced",
    tourType: "reportsTour",
    difficulty: "intermediate"
  },
  {
    id: "admin-tour",
    title: "Admin Features",
    description: "Master advanced administrative capabilities",
    icon: Shield,
    duration: "5 min",
    category: "Advanced",
    tourType: "adminTour",
    difficulty: "advanced"
  }
];

export function TutorialLauncher({ className }: TutorialLauncherProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [, setLocation] = useLocation();
  const { startOnboarding, completedSteps, isStepCompleted } = useOnboarding();

  const handleStartTutorial = (tourType: string) => {
    setIsOpen(false);
    
    // Navigate to the correct page for the tutorial
    const routeMap: Record<string, string> = {
      'dashboard': '/dashboard',
      'teamManagement': '/teams',
      'playerRegistration': '/players',
      'settingsTour': '/settings',
      'reportsTour': '/reports',
      'adminTour': '/users'
    };
    
    const targetRoute = routeMap[tourType];
    if (targetRoute) {
      setLocation(targetRoute);
    }
    
    // Small delay to ensure page navigation and dialog is fully closed before starting tutorial
    setTimeout(() => {
      startOnboarding(tourType);
    }, 500);
  };

  const getTutorialProgress = (tourType: string): number => {
    const tutorial = tutorials.find(t => t.tourType === tourType);
    if (!tutorial) return 0;
    
    // Get actual step count from ONBOARDING_TOURS
    const tourStepsList = ONBOARDING_TOURS[tourType as keyof typeof ONBOARDING_TOURS];
    if (!tourStepsList) return 0;
    
    const totalSteps = tourStepsList.length;
    
    // Count how many steps from this tour are completed
    const completedCount = tourStepsList.filter(step => 
      completedSteps.includes(step.id)
    ).length;
    
    return totalSteps > 0 ? Math.round((completedCount / totalSteps) * 100) : 0;
  };

  const isTutorialCompleted = (tourType: string): boolean => {
    return getTutorialProgress(tourType) === 100;
  };

  const overallProgress = Math.round(
    (tutorials.filter(t => isTutorialCompleted(t.tourType)).length / tutorials.length) * 100
  );

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case 'beginner':
        return 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400';
      case 'intermediate':
        return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400';
      case 'advanced':
        return 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400';
      default:
        return 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400';
    }
  };

  const groupedTutorials = tutorials.reduce((acc, tutorial) => {
    if (!acc[tutorial.category]) {
      acc[tutorial.category] = [];
    }
    acc[tutorial.category].push(tutorial);
    return acc;
  }, {} as Record<string, TutorialItem[]>);

  return (
    <>
      {/* Floating Tutorial Button */}
      <Button
        onClick={() => setIsOpen(true)}
        className="fixed bottom-4 right-4 sm:bottom-6 sm:right-6 h-12 w-12 sm:h-14 sm:w-14 rounded-full shadow-2xl bg-gradient-to-br from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 z-50 group border-2 border-white dark:border-gray-800"
        size="icon"
        data-testid="button-tutorial-launcher"
        aria-label="Open tutorials"
      >
        <GraduationCap className="h-5 w-5 sm:h-6 sm:w-6 text-white group-hover:scale-110 transition-transform" />
      </Button>

      {/* Tutorial Dialog */}
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent 
          className="max-w-[95vw] sm:max-w-[90vw] md:max-w-3xl lg:max-w-4xl max-h-[90vh] overflow-y-auto"
          aria-describedby="tutorial-dialog-description"
        >
          <DialogHeader>
            <div className="flex items-center gap-2 sm:gap-3">
              <div className="p-2 sm:p-3 bg-gradient-to-br from-primary to-primary/80 rounded-xl">
                <BookOpen className="h-5 w-5 sm:h-6 sm:w-6 text-white" />
              </div>
              <div className="flex-1 min-w-0">
                <DialogTitle className="text-lg sm:text-xl md:text-2xl truncate">Interactive Tutorials</DialogTitle>
                <DialogDescription id="tutorial-dialog-description" className="text-xs sm:text-sm">
                  Learn how to use SportsPro with step-by-step guided tours
                </DialogDescription>
              </div>
            </div>
          </DialogHeader>

          {/* Overall Progress */}
          <Card className="border-0 bg-gradient-to-br from-primary/5 to-primary/10 dark:from-primary/10 dark:to-primary/20">
            <CardHeader className="pb-2 sm:pb-3 px-3 sm:px-6">
              <div className="flex items-center justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <CardTitle className="text-base sm:text-lg">Your Progress</CardTitle>
                  <CardDescription className="text-xs sm:text-sm">
                    {tutorials.filter(t => isTutorialCompleted(t.tourType)).length} of {tutorials.length} completed
                  </CardDescription>
                </div>
                {overallProgress === 100 && (
                  <Badge className="bg-green-500 hover:bg-green-600 text-xs whitespace-nowrap">
                    <Trophy className="h-3 w-3 mr-1" />
                    <span className="hidden sm:inline">Expert</span>
                  </Badge>
                )}
              </div>
            </CardHeader>
            <CardContent className="px-3 sm:px-6">
              <div className="space-y-2">
                <div className="flex items-center justify-between text-xs sm:text-sm">
                  <span className="font-medium">Overall Completion</span>
                  <span className="text-primary font-semibold">{overallProgress}%</span>
                </div>
                <Progress value={overallProgress} className="h-2" />
              </div>
            </CardContent>
          </Card>

          {/* Tutorial Categories */}
          <div className="space-y-4 sm:space-y-6 mt-4 sm:mt-6">
            {Object.entries(groupedTutorials).map(([category, categoryTutorials]) => (
              <div key={category}>
                <h3 className="text-base sm:text-lg font-semibold mb-3 sm:mb-4 flex items-center gap-2">
                  {category === "Getting Started" && <Zap className="h-4 w-4 sm:h-5 sm:w-5 text-primary" />}
                  {category === "Core Features" && <Users className="h-4 w-4 sm:h-5 sm:w-5 text-blue-600" />}
                  {category === "Customization" && <Settings className="h-4 w-4 sm:h-5 sm:w-5 text-purple-600" />}
                  {category === "Advanced" && <Shield className="h-4 w-4 sm:h-5 sm:w-5 text-orange-600" />}
                  {category}
                </h3>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                  {categoryTutorials.map((tutorial) => {
                    const progress = getTutorialProgress(tutorial.tourType);
                    const isCompleted = isTutorialCompleted(tutorial.tourType);
                    const TutorialIcon = tutorial.icon;

                    return (
                      <Card 
                        key={tutorial.id}
                        className="hover:shadow-lg transition-all hover:border-primary/50 cursor-pointer group"
                        data-testid={`card-tutorial-${tutorial.id}`}
                      >
                        <CardHeader className="pb-2 sm:pb-3 px-3 sm:px-6">
                          <div className="flex items-start justify-between gap-2">
                            <div className="flex items-start gap-2 sm:gap-3 flex-1 min-w-0">
                              <div className={`p-1.5 sm:p-2 rounded-lg shrink-0 ${
                                category === "Getting Started" ? "bg-green-100 dark:bg-green-900/30" :
                                category === "Core Features" ? "bg-blue-100 dark:bg-blue-900/30" :
                                category === "Customization" ? "bg-purple-100 dark:bg-purple-900/30" :
                                "bg-orange-100 dark:bg-orange-900/30"
                              }`}>
                                <TutorialIcon className={`h-4 w-4 sm:h-5 sm:w-5 ${
                                  category === "Getting Started" ? "text-green-600 dark:text-green-400" :
                                  category === "Core Features" ? "text-blue-600 dark:text-blue-400" :
                                  category === "Customization" ? "text-purple-600 dark:text-purple-400" :
                                  "text-orange-600 dark:text-orange-400"
                                }`} />
                              </div>
                              <div className="flex-1 min-w-0">
                                <CardTitle className="text-sm sm:text-base flex items-center gap-2">
                                  <span className="truncate">{tutorial.title}</span>
                                  {isCompleted && (
                                    <CheckCircle2 className="h-3 w-3 sm:h-4 sm:w-4 text-green-600 shrink-0" />
                                  )}
                                </CardTitle>
                                <CardDescription className="mt-1 text-xs sm:text-sm line-clamp-2">
                                  {tutorial.description}
                                </CardDescription>
                              </div>
                            </div>
                          </div>
                        </CardHeader>
                        <CardContent className="space-y-2 sm:space-y-3 px-3 sm:px-6">
                          <div className="flex items-center gap-2 flex-wrap">
                            <Badge variant="outline" className="text-xs">
                              {tutorial.duration}
                            </Badge>
                            <Badge variant="outline" className={`text-xs ${getDifficultyColor(tutorial.difficulty)}`}>
                              {tutorial.difficulty}
                            </Badge>
                          </div>

                          {progress > 0 && progress < 100 && (
                            <div className="space-y-1">
                              <div className="flex items-center justify-between text-xs">
                                <span className="text-gray-500">Progress</span>
                                <span className="font-medium text-primary">{progress}%</span>
                              </div>
                              <Progress value={progress} className="h-1" />
                            </div>
                          )}

                          <Button
                            onClick={() => handleStartTutorial(tutorial.tourType)}
                            className="w-full h-8 sm:h-9 text-xs sm:text-sm"
                            variant={isCompleted ? "outline" : "default"}
                            data-testid={`button-start-${tutorial.id}`}
                          >
                            {isCompleted ? (
                              <>
                                <CheckCircle2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2" />
                                <span className="hidden xs:inline">Review Tutorial</span>
                                <span className="xs:hidden">Review</span>
                              </>
                            ) : progress > 0 ? (
                              <>
                                <Play className="h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2" />
                                <span className="hidden xs:inline">Continue Tutorial</span>
                                <span className="xs:hidden">Continue</span>
                              </>
                            ) : (
                              <>
                                <Play className="h-3 w-3 sm:h-4 sm:w-4 mr-1 sm:mr-2" />
                                <span className="hidden xs:inline">Start Tutorial</span>
                                <span className="xs:hidden">Start</span>
                              </>
                            )}
                          </Button>
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          <Separator className="my-3 sm:my-4" />

          {/* Help Footer */}
          <div className="p-3 sm:p-4 rounded-lg bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800">
            <div className="flex items-start gap-2 sm:gap-3">
              <BookOpen className="h-4 w-4 sm:h-5 sm:w-5 text-blue-600 dark:text-blue-400 mt-0.5 shrink-0" />
              <div className="flex-1 min-w-0">
                <h4 className="font-medium text-sm sm:text-base text-blue-900 dark:text-blue-200 mb-1">Need More Help?</h4>
                <p className="text-xs sm:text-sm text-blue-800 dark:text-blue-300">
                  Visit our documentation or contact support for additional assistance.
                </p>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
