import { useState } from "react";
import { useQuery, useMutation } 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 { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Target, Calendar, Users, Clock, Trophy, Star, CheckCircle, XCircle } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useToast } from "@/hooks/use-toast";
import { queryClient } from "@/lib/queryClient";

export default function ChallengesPage() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [selectedTab, setSelectedTab] = useState("available");

  const { data: challenges = [], isLoading: challengesLoading } = useQuery({
    queryKey: ["/api/challenges"],
  });

  const { data: userParticipation = [], isLoading: participationLoading } = useQuery({
    queryKey: ["/api/challenges/user", user?.id],
    enabled: !!user?.id,
  });

  const joinChallengeMutation = useMutation({
    mutationFn: async (challengeId: number) => {
      const response = await fetch("/api/challenges/join", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ challengeId, userId: user?.id }),
      });
      if (!response.ok) throw new Error("Failed to join challenge");
      return response.json();
    },
    onSuccess: () => {
      toast({ title: "Joined challenge successfully!" });
      queryClient.invalidateQueries({ queryKey: ["/api/challenges/user"] });
    },
    onError: () => {
      toast({ 
        title: "Failed to join challenge", 
        description: "Please try again later.",
        variant: "destructive" 
      });
    },
  });

  const leaveChallengeMutation = useMutation({
    mutationFn: async (challengeId: number) => {
      const response = await fetch(`/api/challenges/${challengeId}/leave`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId: user?.id }),
      });
      if (!response.ok) throw new Error("Failed to leave challenge");
      return response.json();
    },
    onSuccess: () => {
      toast({ title: "Left challenge successfully!" });
      queryClient.invalidateQueries({ queryKey: ["/api/challenges/user"] });
    },
    onError: () => {
      toast({ 
        title: "Failed to leave challenge", 
        description: "Please try again later.",
        variant: "destructive" 
      });
    },
  });

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case "expert":
        return "bg-red-500";
      case "hard":
        return "bg-orange-500";
      case "medium":
        return "bg-yellow-500";
      default:
        return "bg-green-500";
    }
  };

  const getDifficultyIcon = (difficulty: string) => {
    switch (difficulty) {
      case "expert":
        return <Star className="h-4 w-4" />;
      case "hard":
        return <Target className="h-4 w-4" />;
      case "medium":
        return <Trophy className="h-4 w-4" />;
      default:
        return <CheckCircle className="h-4 w-4" />;
    }
  };

  const isUserParticipating = (challengeId: number) => {
    return userParticipation.some((p: any) => p.challengeId === challengeId);
  };

  const getUserProgress = (challengeId: number) => {
    return userParticipation.find((p: any) => p.challengeId === challengeId);
  };

  const isExpired = (endDate: string) => {
    return new Date(endDate) < new Date();
  };

  const isActive = (startDate: string, endDate: string) => {
    const now = new Date();
    return new Date(startDate) <= now && new Date(endDate) >= now;
  };

  if (challengesLoading || participationLoading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-64 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  const availableChallenges = challenges.filter((challenge: any) => 
    !isExpired(challenge.endDate) && challenge.isActive
  );
  
  const myActiveChallenges = challenges.filter((challenge: any) => 
    isUserParticipating(challenge.id) && isActive(challenge.startDate, challenge.endDate)
  );
  
  const myCompletedChallenges = challenges.filter((challenge: any) => 
    isUserParticipating(challenge.id) && isExpired(challenge.endDate)
  );

  return (
    <div className="container mx-auto px-4 py-8 space-y-8">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Challenges</h1>
          <p className="text-muted-foreground">Compete with others and test your skills</p>
        </div>
      </div>

      {/* Stats Overview */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center space-x-2">
              <Target className="h-5 w-5 text-blue-500" />
              <div>
                <p className="text-2xl font-bold">{myActiveChallenges.length}</p>
                <p className="text-sm text-muted-foreground">Active Challenges</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center space-x-2">
              <Trophy className="h-5 w-5 text-yellow-500" />
              <div>
                <p className="text-2xl font-bold">{myCompletedChallenges.length}</p>
                <p className="text-sm text-muted-foreground">Completed</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center space-x-2">
              <Users className="h-5 w-5 text-green-500" />
              <div>
                <p className="text-2xl font-bold">{availableChallenges.length}</p>
                <p className="text-sm text-muted-foreground">Available</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs value={selectedTab} onValueChange={setSelectedTab} className="space-y-6">
        <TabsList>
          <TabsTrigger value="available">Available ({availableChallenges.length})</TabsTrigger>
          <TabsTrigger value="active">My Active ({myActiveChallenges.length})</TabsTrigger>
          <TabsTrigger value="completed">Completed ({myCompletedChallenges.length})</TabsTrigger>
        </TabsList>

        <TabsContent value="available" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {availableChallenges.map((challenge: any) => {
              const userProgress = getUserProgress(challenge.id);
              const isParticipating = !!userProgress;
              
              return (
                <Card key={challenge.id} className="transition-all hover:shadow-lg">
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-2">
                        <div className={`p-2 rounded-lg ${getDifficultyColor(challenge.difficulty)} text-white`}>
                          {getDifficultyIcon(challenge.difficulty)}
                        </div>
                        <div>
                          <CardTitle className="text-lg">{challenge.name}</CardTitle>
                          <CardDescription>{challenge.description}</CardDescription>
                        </div>
                      </div>
                      <Badge variant="outline" className="capitalize">
                        {challenge.difficulty}
                      </Badge>
                    </div>
                  </CardHeader>
                  
                  <CardContent className="space-y-4">
                    <div className="flex items-center justify-between text-sm text-muted-foreground">
                      <div className="flex items-center space-x-1">
                        <Calendar className="h-4 w-4" />
                        <span>Ends {new Date(challenge.endDate).toLocaleDateString()}</span>
                      </div>
                      {challenge.maxParticipants && (
                        <div className="flex items-center space-x-1">
                          <Users className="h-4 w-4" />
                          <span>{challenge.participantCount || 0}/{challenge.maxParticipants}</span>
                        </div>
                      )}
                    </div>

                    {isParticipating && userProgress && (
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span>Progress</span>
                          <span>{userProgress.progress}/{userProgress.maxProgress}</span>
                        </div>
                        <Progress 
                          value={(userProgress.progress / userProgress.maxProgress) * 100} 
                          className="h-2"
                        />
                      </div>
                    )}

                    <div className="flex items-center justify-between">
                      <div className="text-sm">
                        <span className="font-medium">Rewards:</span>
                        <div className="text-muted-foreground">
                          {challenge.rewards?.points && `+${challenge.rewards.points} points`}
                          {challenge.rewards?.badges && `, ${challenge.rewards.badges.length} badges`}
                        </div>
                      </div>
                      
                      {!isParticipating ? (
                        <Button 
                          size="sm"
                          onClick={() => joinChallengeMutation.mutate(challenge.id)}
                          disabled={joinChallengeMutation.isPending}
                        >
                          Join Challenge
                        </Button>
                      ) : (
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => leaveChallengeMutation.mutate(challenge.id)}
                          disabled={leaveChallengeMutation.isPending}
                        >
                          Leave
                        </Button>
                      )}
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>

          {availableChallenges.length === 0 && (
            <Card className="text-center py-12">
              <CardContent>
                <Target className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <h3 className="text-lg font-semibold mb-2">No Active Challenges</h3>
                <p className="text-muted-foreground">Check back later for new challenges!</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="active" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {myActiveChallenges.map((challenge: any) => {
              const userProgress = getUserProgress(challenge.id);
              
              return (
                <Card key={challenge.id} className="border-blue-200">
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-2">
                        <div className={`p-2 rounded-lg ${getDifficultyColor(challenge.difficulty)} text-white`}>
                          {getDifficultyIcon(challenge.difficulty)}
                        </div>
                        <div>
                          <CardTitle className="text-lg">{challenge.name}</CardTitle>
                          <CardDescription>{challenge.description}</CardDescription>
                        </div>
                      </div>
                      <Badge className="bg-blue-100 text-blue-800">
                        Active
                      </Badge>
                    </div>
                  </CardHeader>
                  
                  <CardContent className="space-y-4">
                    {userProgress && (
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span>Your Progress</span>
                          <span>{userProgress.progress}/{userProgress.maxProgress}</span>
                        </div>
                        <Progress 
                          value={(userProgress.progress / userProgress.maxProgress) * 100} 
                          className="h-3"
                        />
                        {userProgress.rank && (
                          <p className="text-sm text-muted-foreground">
                            Current Rank: #{userProgress.rank}
                          </p>
                        )}
                      </div>
                    )}

                    <div className="flex items-center justify-between text-sm text-muted-foreground">
                      <div className="flex items-center space-x-1">
                        <Clock className="h-4 w-4" />
                        <span>Ends {new Date(challenge.endDate).toLocaleDateString()}</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>

          {myActiveChallenges.length === 0 && (
            <Card className="text-center py-12">
              <CardContent>
                <Target className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <h3 className="text-lg font-semibold mb-2">No Active Challenges</h3>
                <p className="text-muted-foreground">Join some challenges from the Available tab!</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="completed" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {myCompletedChallenges.map((challenge: any) => {
              const userProgress = getUserProgress(challenge.id);
              
              return (
                <Card key={challenge.id} className="border-green-200">
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-2">
                        <div className="p-2 rounded-lg bg-green-500 text-white">
                          <CheckCircle className="h-4 w-4" />
                        </div>
                        <div>
                          <CardTitle className="text-lg">{challenge.name}</CardTitle>
                          <CardDescription>{challenge.description}</CardDescription>
                        </div>
                      </div>
                      <Badge className="bg-green-100 text-green-800">
                        Completed
                      </Badge>
                    </div>
                  </CardHeader>
                  
                  <CardContent className="space-y-4">
                    {userProgress && (
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span>Final Progress</span>
                          <span>{userProgress.progress}/{userProgress.maxProgress}</span>
                        </div>
                        <Progress 
                          value={(userProgress.progress / userProgress.maxProgress) * 100} 
                          className="h-2"
                        />
                        {userProgress.rank && (
                          <p className="text-sm font-medium">
                            Final Rank: #{userProgress.rank}
                          </p>
                        )}
                        {userProgress.completedAt && (
                          <p className="text-xs text-muted-foreground">
                            Completed {new Date(userProgress.completedAt).toLocaleDateString()}
                          </p>
                        )}
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })}
          </div>

          {myCompletedChallenges.length === 0 && (
            <Card className="text-center py-12">
              <CardContent>
                <Trophy className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <h3 className="text-lg font-semibold mb-2">No Completed Challenges</h3>
                <p className="text-muted-foreground">Complete some challenges to see them here!</p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}