import { useSport } from "@/hooks/useSport";
import { useAuth } from "@/hooks/useAuth";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { 
  Trophy, 
  Users, 
  Calendar, 
  Plus, 
  Eye, 
  ArrowRight,
  TrendingUp,
  Activity,
  DollarSign,
  Award,
  BarChart3,
  MapPin,
  Sparkles
} from "lucide-react";
import { useLocation } from "wouter";
import { cn } from "@/lib/utils";
import type { Team } from "@shared/schema";
import { getSportIcon, getSportIconColor } from "@/lib/sport-icons";
import type { SportType } from "@shared/sports";

export default function Dashboard() {
  const { sportName, currentSport, teamSize, isTeamSport } = useSport();
  const { user } = useAuth();
  const [, setLocation] = useLocation();

  const { data: teams = [], isLoading } = useQuery<Team[]>({
    queryKey: ["/api/teams"],
  });

  const totalTeams = teams.length;
  const activeTeams = teams.filter(t => t.status === 'active').length;
  const inactiveTeams = totalTeams - activeTeams;

  const getSportWelcomeMessage = () => {
    const sportMessages: Record<string, string> = {
      football: "Ready for some football action!",
      rugby: "Welcome to the rugby field!",
      cricket: "Time for cricket!",
      baseball: "Batter up!",
      basketball: "Hit the court!",
      hockey: "Face off time!",
      netball: "Seven players, one goal!",
      soccer: "Beautiful game awaits!",
      badminton: "Shuttlecock ready!",
      volleyball: "Spike it!"
    };
    
    return sportMessages[currentSport as keyof typeof sportMessages] || "Welcome to your sports management dashboard!";
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
        <div className="container mx-auto px-6 py-8">
          <div className="space-y-6">
            <div className="space-y-2">
              <Skeleton className="h-10 w-64" />
              <Skeleton className="h-5 w-96" />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {[1, 2, 3, 4].map((i) => (
                <Skeleton key={i} className="h-36" />
              ))}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[1, 2, 3].map((i) => (
                <Skeleton key={i} className="h-64" />
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800" data-tour="welcome">
      <div className="container mx-auto px-6 py-8">
        {/* Welcome Header */}
        <div className="mb-8">
          <div className="flex items-center gap-2 mb-2">
            <h1 className="text-4xl font-bold text-gray-900 dark:text-white">
              Welcome back, {(user as any)?.firstName}! 👋
            </h1>
          </div>
          <p className="text-lg text-gray-600 dark:text-gray-400 flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            {getSportWelcomeMessage()}
          </p>
        </div>

        {/* Quick Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          {/* Total Teams */}
          <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-blue-500 to-blue-600 text-white overflow-hidden group">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-medium text-blue-100">Total Teams</CardTitle>
                <div className="p-2 bg-white/20 rounded-lg backdrop-blur-sm group-hover:scale-110 transition-transform">
                  <Users className="h-5 w-5" />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold mb-1">{totalTeams}</div>
              <p className="text-sm text-blue-100">
                {activeTeams} active, {inactiveTeams} inactive
              </p>
            </CardContent>
          </Card>

          {/* Sport Info */}
          <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-green-500 to-green-600 text-white overflow-hidden group">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-medium text-green-100">Sport Type</CardTitle>
                <div className="p-2 bg-white/20 rounded-lg backdrop-blur-sm group-hover:scale-110 transition-transform">
                  {(() => {
                    const SportIcon = getSportIcon(currentSport as SportType);
                    return <SportIcon className="h-5 w-5" />;
                  })()}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold mb-1 capitalize">{sportName}</div>
              <p className="text-sm text-green-100">
                {isTeamSport ? `${teamSize} players per team` : 'Individual sport'}
              </p>
            </CardContent>
          </Card>

          {/* Activity */}
          <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-purple-500 to-purple-600 text-white overflow-hidden group">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-medium text-purple-100">Activity</CardTitle>
                <div className="p-2 bg-white/20 rounded-lg backdrop-blur-sm group-hover:scale-110 transition-transform">
                  <Activity className="h-5 w-5" />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-4xl font-bold mb-1">24/7</div>
              <p className="text-sm text-purple-100">Real-time tracking</p>
            </CardContent>
          </Card>

          {/* Performance */}
          <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-orange-500 to-orange-600 text-white overflow-hidden group">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-medium text-orange-100">Performance</CardTitle>
                <div className="p-2 bg-white/20 rounded-lg backdrop-blur-sm group-hover:scale-110 transition-transform">
                  <TrendingUp className="h-5 w-5" />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <a href="/reports" className="block">
                <Button 
                  variant="secondary" 
                  size="sm" 
                  className="w-full bg-white/20 hover:bg-white/30 border-0 text-white backdrop-blur-sm" 
                  data-testid="view-reports"
                  asChild
                >
                  <span>View Reports</span>
                </Button>
              </a>
            </CardContent>
          </Card>
        </div>

        {/* Teams Section */}
        <div className="mb-8" data-tour="teams-card">
          <div className="flex justify-between items-center mb-6">
            <div>
              <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Your Teams</h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">Manage and track all your teams</p>
            </div>
            <a href="/teams">
              <Button 
                className="group" 
                size="sm" 
                data-testid="view-all-teams"
              >
                View All
                <ArrowRight className="ml-2 h-4 w-4 group-hover:translate-x-1 transition-transform" />
              </Button>
            </a>
          </div>

          {teams.length === 0 ? (
            <Card className="border-2 border-dashed border-gray-300 dark:border-gray-700 bg-white/50 dark:bg-gray-800/50 backdrop-blur-sm">
              <CardContent className="py-16">
                <div className="text-center max-w-md mx-auto">
                  <div className="w-20 h-20 bg-gradient-to-br from-primary to-primary/80 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg">
                    <Users className="h-10 w-10 text-white" />
                  </div>
                  <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-3">No Teams Yet</h3>
                  <p className="text-gray-600 dark:text-gray-400 mb-6">
                    Get started by creating your first team. You'll be able to add players, coaches, and track performance.
                  </p>
                  <a href="/teams/new">
                    <Button 
                      size="lg" 
                      className="group" 
                      data-testid="create-first-team"
                    >
                      <Plus className="mr-2 h-5 w-5 group-hover:rotate-90 transition-transform" />
                      Create Your First Team
                    </Button>
                  </a>
                </div>
              </CardContent>
            </Card>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {teams.slice(0, 6).map((team) => (
                <Card 
                  key={team.id} 
                  className="group hover:shadow-2xl transition-all duration-300 border-0 shadow-lg overflow-hidden bg-white dark:bg-gray-800" 
                  data-testid={`team-card-${team.id}`}
                >
                  <div className="absolute inset-0 bg-gradient-to-br from-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
                  <CardHeader className="pb-4 relative">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-4">
                        <Avatar className="h-14 w-14 ring-2 ring-primary/10 group-hover:ring-primary/30 transition-all shadow-lg">
                          <AvatarImage src={team.logoUrl || undefined} alt={`${team.name} logo`} />
                          <AvatarFallback className="bg-gradient-to-br from-primary to-primary/80 text-white font-bold text-lg">
                            {team.name.substring(0, 2).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <CardTitle className="text-lg group-hover:text-primary transition-colors line-clamp-1">
                            {team.name}
                          </CardTitle>
                          <Badge 
                            variant={team.status === 'active' ? 'default' : 'secondary'} 
                            className="mt-1.5"
                          >
                            {team.status}
                          </Badge>
                        </div>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="relative">
                    <div className="space-y-2.5 mb-5">
                      <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                        {(() => {
                          const SportIcon = getSportIcon(team.sport as SportType);
                          const colors = getSportIconColor(team.sport as SportType);
                          return (
                            <div className={`p-1.5 ${colors.bg} ${colors.darkBg} rounded-md mr-2.5`}>
                              <SportIcon className={`h-3.5 w-3.5 ${colors.text} ${colors.darkText}`} />
                            </div>
                          );
                        })()}
                        <span className="capitalize font-medium">{team.sport}</span>
                      </div>
                      {team.league && (
                        <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                          <div className="p-1.5 bg-yellow-100 dark:bg-yellow-900/30 rounded-md mr-2.5">
                            <Trophy className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-400" />
                          </div>
                          <span className="font-medium">{team.league}</span>
                        </div>
                      )}
                      {team.homeVenue && (
                        <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                          <div className="p-1.5 bg-green-100 dark:bg-green-900/30 rounded-md mr-2.5">
                            <MapPin className="h-3.5 w-3.5 text-green-600 dark:text-green-400" />
                          </div>
                          <span className="font-medium line-clamp-1">{team.homeVenue}</span>
                        </div>
                      )}
                    </div>

                    <div className="flex gap-2">
                      <a href={`/teams/${team.id}`} className="flex-1">
                        <Button 
                          size="sm" 
                          className="w-full group/btn" 
                          data-testid={`view-team-${team.id}`}
                        >
                          <Eye className="h-3.5 w-3.5 mr-1.5 group-hover/btn:scale-110 transition-transform" />
                          View
                        </Button>
                      </a>
                      <a href={`/teams/${team.id}/edit`} className="flex-1">
                        <Button 
                          size="sm" 
                          variant="outline" 
                          className="w-full" 
                          data-testid={`edit-team-${team.id}`}
                        >
                          Edit
                        </Button>
                      </a>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>

        {/* Quick Access Links */}
        {teams.length > 0 && (
          <div>
            <div className="mb-6">
              <h3 className="text-2xl font-bold text-gray-900 dark:text-white">Quick Access</h3>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">Navigate to commonly used features</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <a href="/players" className="block">
                <Card 
                  className="cursor-pointer hover:shadow-xl transition-all duration-300 group border-0 shadow-md bg-white dark:bg-gray-800"
                >
                <CardContent className="p-6">
                  <div className="flex items-start gap-4">
                    <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-xl group-hover:scale-110 transition-transform">
                      <Users className="h-6 w-6 text-blue-600 dark:text-blue-400" />
                    </div>
                    <div className="flex-1">
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-1 group-hover:text-primary transition-colors">
                        Players
                      </h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Manage roster</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              </a>

              <a href="/coaches" className="block">
                <Card 
                  className="cursor-pointer hover:shadow-xl transition-all duration-300 group border-0 shadow-md bg-white dark:bg-gray-800"
                >
                <CardContent className="p-6">
                  <div className="flex items-start gap-4">
                    <div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-xl group-hover:scale-110 transition-transform">
                      <Award className="h-6 w-6 text-green-600 dark:text-green-400" />
                    </div>
                    <div className="flex-1">
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-1 group-hover:text-primary transition-colors">
                        Coaches
                      </h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Coaching staff</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              </a>

              <a href="/fixtures" className="block">
                <Card 
                  className="cursor-pointer hover:shadow-xl transition-all duration-300 group border-0 shadow-md bg-white dark:bg-gray-800"
                >
                <CardContent className="p-6">
                  <div className="flex items-start gap-4">
                    <div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-xl group-hover:scale-110 transition-transform">
                      <Calendar className="h-6 w-6 text-purple-600 dark:text-purple-400" />
                    </div>
                    <div className="flex-1">
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-1 group-hover:text-primary transition-colors">
                        Fixtures
                      </h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400">View schedule</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              </a>

              <a href="/reports" className="block">
                <Card 
                  className="cursor-pointer hover:shadow-xl transition-all duration-300 group border-0 shadow-md bg-white dark:bg-gray-800"
                >
                <CardContent className="p-6">
                  <div className="flex items-start gap-4">
                    <div className="p-3 bg-orange-100 dark:bg-orange-900/30 rounded-xl group-hover:scale-110 transition-transform">
                      <BarChart3 className="h-6 w-6 text-orange-600 dark:text-orange-400" />
                    </div>
                    <div className="flex-1">
                      <h4 className="font-semibold text-gray-900 dark:text-white mb-1 group-hover:text-primary transition-colors">
                        Analytics
                      </h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400">View insights</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              </a>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
