import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { TrendingUp, Users, Activity, Target, BarChart3, Download } from "lucide-react";
import {
  ResponsiveContainer,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  BarChart,
  Bar,
  LineChart,
  Line,
  Legend,
  PieChart,
  Pie,
  Cell,
} from "recharts";

const COLORS = {
  primary: "#1976D2",
  secondary: "#FF6B35",
  success: "#4CAF50",
  warning: "#FF9800",
  error: "#F44336",
};

// Sample performance data
const performanceData = [
  { month: "Jan", goals: 45, assists: 23, points: 68 },
  { month: "Feb", goals: 52, assists: 28, points: 80 },
  { month: "Mar", goals: 48, assists: 31, points: 79 },
  { month: "Apr", goals: 61, assists: 35, points: 96 },
  { month: "May", goals: 55, assists: 29, points: 84 },
  { month: "Jun", goals: 67, assists: 42, points: 109 },
];

const attendanceData = [
  { date: "Week 1", attendance: 95 },
  { date: "Week 2", attendance: 88 },
  { date: "Week 3", attendance: 92 },
  { date: "Week 4", attendance: 96 },
  { date: "Week 5", attendance: 89 },
  { date: "Week 6", attendance: 94 },
];

const injuryData = [
  { type: "Minor", count: 12, color: COLORS.success },
  { type: "Moderate", count: 8, color: COLORS.warning },
  { type: "Serious", count: 3, color: COLORS.error },
];

export default function Analytics() {
  const { data: stats, isLoading: statsLoading } = useQuery({
    queryKey: ["/api/dashboard/stats"],
  });

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

  if (statsLoading) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-6">
          <div className="h-8 bg-gray-200 rounded w-48"></div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {[...Array(4)].map((_, i) => (
              <div key={i} className="h-32 bg-gray-200 rounded-xl"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-3xl font-bold text-gray-900">Advanced Analytics</h2>
            <p className="text-gray-600">Comprehensive performance insights and detailed reports</p>
          </div>
          <div className="flex space-x-4">
            <Select defaultValue="all">
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Teams</SelectItem>
                {teams?.map((team: any) => (
                  <SelectItem key={team.id} value={team.id.toString()}>
                    {team.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button>
              <Download className="h-4 w-4 mr-2" />
              Export Report
            </Button>
          </div>
        </div>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Performance Score</p>
                <p className="text-3xl font-bold text-gray-900">87.5</p>
                <p className="text-success text-sm font-medium mt-1 flex items-center">
                  <TrendingUp className="h-4 w-4 mr-1" />
                  +5.2% from last month
                </p>
              </div>
              <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center">
                <Target className="text-primary text-xl" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Avg Attendance</p>
                <p className="text-3xl font-bold text-gray-900">92.3%</p>
                <p className="text-success text-sm font-medium mt-1 flex items-center">
                  <Activity className="h-4 w-4 mr-1" />
                  Excellent rate
                </p>
              </div>
              <div className="w-12 h-12 bg-secondary/10 rounded-lg flex items-center justify-center">
                <Users className="text-secondary text-xl" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Injury Rate</p>
                <p className="text-3xl font-bold text-gray-900">2.1%</p>
                <p className="text-success text-sm font-medium mt-1 flex items-center">
                  <TrendingUp className="h-4 w-4 mr-1" />
                  Below average
                </p>
              </div>
              <div className="w-12 h-12 bg-success/10 rounded-lg flex items-center justify-center">
                <Activity className="text-success text-xl" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-gray-600 text-sm font-medium">Training Hours</p>
                <p className="text-3xl font-bold text-gray-900">247</p>
                <p className="text-gray-500 text-sm font-medium mt-1 flex items-center">
                  <BarChart3 className="h-4 w-4 mr-1" />
                  This month
                </p>
              </div>
              <div className="w-12 h-12 bg-warning/10 rounded-lg flex items-center justify-center">
                <BarChart3 className="text-warning text-xl" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        {/* Performance Trends */}
        <Card>
          <CardHeader>
            <CardTitle>Performance Trends</CardTitle>
            <CardDescription>Goals, assists, and total points over time</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={performanceData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip />
                <Legend />
                <Area 
                  type="monotone" 
                  dataKey="points" 
                  stackId="1"
                  stroke={COLORS.primary}
                  fill={COLORS.primary}
                  fillOpacity={0.6}
                  name="Total Points"
                />
                <Area 
                  type="monotone" 
                  dataKey="goals" 
                  stackId="2"
                  stroke={COLORS.secondary}
                  fill={COLORS.secondary}
                  fillOpacity={0.6}
                  name="Goals"
                />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Attendance Tracking */}
        <Card>
          <CardHeader>
            <CardTitle>Attendance Tracking</CardTitle>
            <CardDescription>Weekly attendance percentage</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={attendanceData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} />
                <YAxis tick={{ fontSize: 12 }} domain={[80, 100]} />
                <Tooltip />
                <Line 
                  type="monotone" 
                  dataKey="attendance" 
                  stroke={COLORS.success}
                  strokeWidth={3}
                  dot={{ fill: COLORS.success, strokeWidth: 2, r: 4 }}
                  name="Attendance %"
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Injury Analysis */}
        <Card>
          <CardHeader>
            <CardTitle>Injury Analysis</CardTitle>
            <CardDescription>Distribution of injury types this season</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={injuryData}
                  cx="50%"
                  cy="50%"
                  outerRadius={100}
                  dataKey="count"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                >
                  {injuryData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Team Comparison */}
        <Card>
          <CardHeader>
            <CardTitle>Team Performance Comparison</CardTitle>
            <CardDescription>Comparative analysis across teams</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {stats?.playersByTeam?.slice(0, 5).map((team: any, index: number) => (
                <div key={team.teamName} className="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
                  <div className="flex items-center space-x-3">
                    <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center text-white font-bold">
                      {index + 1}
                    </div>
                    <div>
                      <h4 className="font-semibold text-gray-900">{team.teamName}</h4>
                      <p className="text-sm text-gray-500">{team.playerCount} players</p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge className="bg-success text-white">
                      {85 + index * 2}% Performance
                    </Badge>
                  </div>
                </div>
              )) || (
                <p className="text-gray-500 text-center py-8">
                  No team data available. Create teams to see analytics.
                </p>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Detailed Reports Section */}
      <Card>
        <CardHeader>
          <CardTitle>Detailed Reports</CardTitle>
          <CardDescription>Generate comprehensive reports for stakeholders</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Button variant="outline" className="h-auto p-4 flex-col space-y-2">
              <BarChart3 className="h-8 w-8 text-primary" />
              <div className="text-center">
                <p className="font-semibold">Performance Report</p>
                <p className="text-xs text-gray-500">Monthly team analysis</p>
              </div>
            </Button>
            
            <Button variant="outline" className="h-auto p-4 flex-col space-y-2">
              <Users className="h-8 w-8 text-secondary" />
              <div className="text-center">
                <p className="font-semibold">Player Statistics</p>
                <p className="text-xs text-gray-500">Individual metrics</p>
              </div>
            </Button>
            
            <Button variant="outline" className="h-auto p-4 flex-col space-y-2">
              <Activity className="h-8 w-8 text-success" />
              <div className="text-center">
                <p className="font-semibold">Health & Safety</p>
                <p className="text-xs text-gray-500">Injury prevention data</p>
              </div>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}