import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar } from "recharts";
import { TrendingUp, TrendingDown, Target, Award, Activity, Timer, Users, Trophy } from "lucide-react";
import { type Player, type Team } from "@shared/schema";

export default function Performance() {
  const [selectedPlayer, setSelectedPlayer] = useState<string>("");
  const [selectedTeam, setSelectedTeam] = useState<string>("");
  const [timeframe, setTimeframe] = useState<string>("6months");

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

  const { data: players = [] } = useQuery<Player[]>({
    queryKey: ["/api/players"],
  });

  // Mock performance data - in real app this would come from tracking systems
  const performanceData = {
    playerStats: {
      "22": {
        name: "John Doe",
        position: "Fly-half",
        totalMinutes: 1420,
        matchesPlayed: 18,
        tries: 8,
        conversions: 15,
        penalties: 12,
        tackles: 89,
        tackleSuccess: 85,
        lineoutSuccess: 92,
        scrumSuccess: 88,
        fitnessScore: 87,
        form: [78, 82, 85, 87, 89, 91, 88, 85, 87, 90, 87, 89],
      }
    },
    teamStats: {
      "10": {
        name: "Barewa",
        matchesPlayed: 20,
        wins: 14,
        draws: 2,
        losses: 4,
        pointsFor: 456,
        pointsAgainst: 312,
        averageAttendance: 92,
        injuryRate: 8,
        fitnessAverage: 84,
      }
    }
  };

  const fitnessData = [
    { month: "Jan", fitness: 78, stamina: 82, strength: 75 },
    { month: "Feb", fitness: 82, stamina: 85, strength: 78 },
    { month: "Mar", fitness: 85, stamina: 87, strength: 82 },
    { month: "Apr", fitness: 87, stamina: 89, strength: 85 },
    { month: "May", fitness: 89, stamina: 91, strength: 87 },
    { month: "Jun", fitness: 91, stamina: 88, strength: 89 },
  ];

  const skillsData = [
    { skill: "Tackling", value: 85 },
    { skill: "Passing", value: 92 },
    { skill: "Kicking", value: 78 },
    { skill: "Rucking", value: 88 },
    { skill: "Lineout", value: 92 },
    { skill: "Scrum", value: 88 },
  ];

  const matchPerformance = [
    { match: "vs Eagles", rating: 8.5, tries: 2, tackles: 12, minutes: 80 },
    { match: "vs Lions", rating: 7.8, tries: 1, tackles: 15, minutes: 75 },
    { match: "vs Tigers", rating: 9.2, tries: 3, tackles: 8, minutes: 80 },
    { match: "vs Sharks", rating: 8.1, tries: 1, tackles: 14, minutes: 80 },
    { match: "vs Bulls", rating: 7.5, tries: 0, tackles: 18, minutes: 65 },
  ];

  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8'];

  const currentPlayer = selectedPlayer ? performanceData.playerStats[selectedPlayer as keyof typeof performanceData.playerStats] : null;
  const currentTeam = selectedTeam ? performanceData.teamStats[selectedTeam as keyof typeof performanceData.teamStats] : null;

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Performance Analytics</h1>
          <p className="text-gray-600">Track player and team performance metrics</p>
        </div>
        
        <div className="flex gap-4">
          <Select value={timeframe} onValueChange={setTimeframe}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="1month">Last Month</SelectItem>
              <SelectItem value="3months">Last 3 Months</SelectItem>
              <SelectItem value="6months">Last 6 Months</SelectItem>
              <SelectItem value="1year">Last Year</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <Tabs defaultValue="overview" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="players">Player Analytics</TabsTrigger>
          <TabsTrigger value="teams">Team Performance</TabsTrigger>
          <TabsTrigger value="fitness">Fitness Tracking</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Matches</CardTitle>
                <Trophy className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">42</div>
                <p className="text-xs text-muted-foreground">
                  <span className="text-green-600">+3</span> from last period
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Win Rate</CardTitle>
                <Target className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">78%</div>
                <p className="text-xs text-muted-foreground">
                  <span className="text-green-600">+5%</span> from last period
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Avg Fitness</CardTitle>
                <Activity className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">84</div>
                <p className="text-xs text-muted-foreground">
                  <span className="text-green-600">+2</span> from last period
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Injury Rate</CardTitle>
                <Timer className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">8%</div>
                <p className="text-xs text-muted-foreground">
                  <span className="text-red-600">+1%</span> from last period
                </p>
              </CardContent>
            </Card>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Team Performance Trend</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={fitnessData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Line type="monotone" dataKey="fitness" stroke="#8884d8" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Top Performers</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {players.slice(0, 5).map((player, index) => (
                    <div key={player.id} className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <Badge variant={index === 0 ? "default" : "secondary"}>
                          {index + 1}
                        </Badge>
                        <div>
                          <p className="font-medium">{player.firstName} {player.lastName}</p>
                          <p className="text-sm text-gray-600">{player.position}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="font-semibold">{(95 - index * 3).toFixed(1)}</p>
                        <p className="text-sm text-gray-600">Performance Score</p>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="players" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Player Selection</CardTitle>
              <CardDescription>Select a player to view detailed performance analytics</CardDescription>
            </CardHeader>
            <CardContent>
              <Select value={selectedPlayer} onValueChange={setSelectedPlayer}>
                <SelectTrigger className="w-64">
                  <SelectValue placeholder="Select a player" />
                </SelectTrigger>
                <SelectContent>
                  {players.map((player) => (
                    <SelectItem key={player.id} value={player.id.toString()}>
                      {player.firstName} {player.lastName} - {player.position}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </CardContent>
          </Card>

          {currentPlayer && (
            <>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Matches Played</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentPlayer.matchesPlayed}</div>
                    <div className="text-sm text-gray-600">{currentPlayer.totalMinutes} minutes</div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Tries Scored</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentPlayer.tries}</div>
                    <div className="text-sm text-gray-600">
                      {(currentPlayer.tries / currentPlayer.matchesPlayed).toFixed(1)} per game
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Tackle Success</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentPlayer.tackleSuccess}%</div>
                    <div className="text-sm text-gray-600">{currentPlayer.tackles} total tackles</div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Fitness Score</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentPlayer.fitnessScore}</div>
                    <Progress value={currentPlayer.fitnessScore} className="mt-2" />
                  </CardContent>
                </Card>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle>Form Trend</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <LineChart data={currentPlayer.form.map((score, index) => ({ 
                        match: `Match ${index + 1}`, 
                        score 
                      }))}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="match" />
                        <YAxis domain={[60, 100]} />
                        <Tooltip />
                        <Line type="monotone" dataKey="score" stroke="#8884d8" strokeWidth={2} />
                      </LineChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>Skills Radar</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <RadarChart data={skillsData}>
                        <PolarGrid />
                        <PolarAngleAxis dataKey="skill" />
                        <PolarRadiusAxis angle={90} domain={[0, 100]} />
                        <Radar
                          name="Skills"
                          dataKey="value"
                          stroke="#8884d8"
                          fill="#8884d8"
                          fillOpacity={0.6}
                        />
                      </RadarChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>
              </div>

              <Card>
                <CardHeader>
                  <CardTitle>Recent Match Performance</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {matchPerformance.map((match, index) => (
                      <div key={index} className="flex items-center justify-between p-4 border rounded-lg">
                        <div>
                          <p className="font-medium">{match.match}</p>
                          <p className="text-sm text-gray-600">{match.minutes} minutes played</p>
                        </div>
                        <div className="grid grid-cols-3 gap-4 text-center">
                          <div>
                            <p className="text-sm text-gray-600">Rating</p>
                            <Badge variant={match.rating >= 8 ? "default" : "secondary"}>
                              {match.rating}
                            </Badge>
                          </div>
                          <div>
                            <p className="text-sm text-gray-600">Tries</p>
                            <p className="font-semibold">{match.tries}</p>
                          </div>
                          <div>
                            <p className="text-sm text-gray-600">Tackles</p>
                            <p className="font-semibold">{match.tackles}</p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </>
          )}
        </TabsContent>

        <TabsContent value="teams" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Team Selection</CardTitle>
              <CardDescription>Select a team to view performance metrics</CardDescription>
            </CardHeader>
            <CardContent>
              <Select value={selectedTeam} onValueChange={setSelectedTeam}>
                <SelectTrigger className="w-64">
                  <SelectValue placeholder="Select a team" />
                </SelectTrigger>
                <SelectContent>
                  {teams.map((team) => (
                    <SelectItem key={team.id} value={team.id.toString()}>
                      {team.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </CardContent>
          </Card>

          {currentTeam && (
            <>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Match Record</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      {currentTeam.wins}-{currentTeam.draws}-{currentTeam.losses}
                    </div>
                    <div className="text-sm text-gray-600">
                      {Math.round((currentTeam.wins / currentTeam.matchesPlayed) * 100)}% win rate
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Points Difference</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">
                      +{currentTeam.pointsFor - currentTeam.pointsAgainst}
                    </div>
                    <div className="text-sm text-gray-600">
                      {currentTeam.pointsFor} for, {currentTeam.pointsAgainst} against
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Attendance</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentTeam.averageAttendance}%</div>
                    <Progress value={currentTeam.averageAttendance} className="mt-2" />
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm">Team Fitness</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{currentTeam.fitnessAverage}</div>
                    <Progress value={currentTeam.fitnessAverage} className="mt-2" />
                  </CardContent>
                </Card>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle>Performance Distribution</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <PieChart>
                        <Pie
                          data={[
                            { name: "Wins", value: currentTeam.wins, fill: "#00C49F" },
                            { name: "Draws", value: currentTeam.draws, fill: "#FFBB28" },
                            { name: "Losses", value: currentTeam.losses, fill: "#FF8042" },
                          ]}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                          outerRadius={80}
                          fill="#8884d8"
                          dataKey="value"
                        >
                          {[
                            { name: "Wins", value: currentTeam.wins, fill: "#00C49F" },
                            { name: "Draws", value: currentTeam.draws, fill: "#FFBB28" },
                            { name: "Losses", value: currentTeam.losses, fill: "#FF8042" },
                          ].map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.fill} />
                          ))}
                        </Pie>
                        <Tooltip />
                      </PieChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>Monthly Points</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <ResponsiveContainer width="100%" height={300}>
                      <BarChart data={[
                        { month: "Jan", points: 45 },
                        { month: "Feb", points: 38 },
                        { month: "Mar", points: 52 },
                        { month: "Apr", points: 41 },
                        { month: "May", points: 48 },
                        { month: "Jun", points: 55 },
                      ]}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="month" />
                        <YAxis />
                        <Tooltip />
                        <Bar dataKey="points" fill="#8884d8" />
                      </BarChart>
                    </ResponsiveContainer>
                  </CardContent>
                </Card>
              </div>
            </>
          )}
        </TabsContent>

        <TabsContent value="fitness" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Fitness Progression</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={fitnessData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Line type="monotone" dataKey="fitness" stroke="#8884d8" strokeWidth={2} />
                    <Line type="monotone" dataKey="stamina" stroke="#82ca9d" strokeWidth={2} />
                    <Line type="monotone" dataKey="strength" stroke="#ffc658" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Fitness Distribution</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between mb-2">
                      <span>Excellent (90-100)</span>
                      <span>23%</span>
                    </div>
                    <Progress value={23} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between mb-2">
                      <span>Good (80-89)</span>
                      <span>45%</span>
                    </div>
                    <Progress value={45} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between mb-2">
                      <span>Average (70-79)</span>
                      <span>24%</span>
                    </div>
                    <Progress value={24} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between mb-2">
                      <span>Below Average (&lt;70)</span>
                      <span>8%</span>
                    </div>
                    <Progress value={8} className="h-2" />
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardHeader>
              <CardTitle>Individual Fitness Scores</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {players.slice(0, 6).map((player) => (
                  <div key={player.id} className="p-4 border rounded-lg">
                    <div className="flex justify-between items-center mb-2">
                      <h4 className="font-medium">{player.firstName} {player.lastName}</h4>
                      <Badge variant={Math.random() > 0.3 ? "default" : "secondary"}>
                        {(75 + Math.random() * 20).toFixed(0)}
                      </Badge>
                    </div>
                    <p className="text-sm text-gray-600">{player.position}</p>
                    <Progress value={75 + Math.random() * 20} className="mt-2" />
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}