import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Calendar, Download, TrendingUp, Users, DollarSign, Trophy } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts";

interface FixturesReport {
  total: number;
  completed: number;
  upcoming: number;
  byMonth: Array<{ month: string; count: number }>;
  byTeam: Array<{ teamId: number; teamName: string; matches: number }>;
}

interface AttendanceReport {
  totalSessions: number;
  totalAttendance: number;
  averageAttendanceRate: number;
  byMonth: Array<{ month: string; rate: number }>;
  topAttenders: Array<{ playerId: number; playerName: string; attendanceRate: number; sessionsAttended: number }>;
  absentees: Array<{ playerId: number; playerName: string; absences: number }>;
}

interface RevenueReport {
  totalRevenue: number;
  byMonth: Array<{ month: string; amount: number }>;
  byType: Array<{ type: string; amount: number }>;
  outstandingPayments: number;
  paidCount: number;
  pendingCount: number;
}

interface TopScorersReport {
  topPlayers: Array<{ 
    playerId: number; 
    playerName: string; 
    position: string;
    teamName: string;
    stats: {
      matches: number;
      attendanceRate: number;
    };
  }>;
}

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

export function Reports() {
  const [dateRange, setDateRange] = useState<string>("all");
  const [selectedTeam, setSelectedTeam] = useState<string>("all");

  const { data: fixturesData, isLoading: fixturesLoading } = useQuery<FixturesReport>({
    queryKey: ["/api/reports/fixtures", dateRange, selectedTeam],
  });

  const { data: attendanceData, isLoading: attendanceLoading } = useQuery<AttendanceReport>({
    queryKey: ["/api/reports/attendance", dateRange, selectedTeam],
  });

  const { data: revenueData, isLoading: revenueLoading } = useQuery<RevenueReport>({
    queryKey: ["/api/reports/revenue", dateRange],
  });

  const { data: topScorersData, isLoading: topScorersLoading } = useQuery<TopScorersReport>({
    queryKey: ["/api/reports/top-scorers", selectedTeam],
  });

  const handleExport = async (reportType: string) => {
    try {
      const response = await fetch(`/api/reports/export/${reportType}`);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${reportType}-report-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('Export failed:', error);
    }
  };

  return (
    <div className="p-6 lg:p-8 bg-white dark:bg-gray-950">
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              Reports & Analytics
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              Comprehensive insights and analytics for your sports organization
            </p>
          </div>
          <div className="flex gap-2">
            <Select value={dateRange} onValueChange={setDateRange}>
              <SelectTrigger className="w-[180px] bg-white dark:bg-gray-900" data-testid="select-date-range">
                <SelectValue placeholder="Select period" />
              </SelectTrigger>
              <SelectContent className="bg-white dark:bg-gray-900">
                <SelectItem value="all">All Time</SelectItem>
                <SelectItem value="this-month">This Month</SelectItem>
                <SelectItem value="last-month">Last Month</SelectItem>
                <SelectItem value="this-year">This Year</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <Tabs defaultValue="fixtures" className="space-y-6">
          <TabsList className="bg-gray-100 dark:bg-gray-900">
            <TabsTrigger value="fixtures" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-800" data-testid="tab-fixtures">
              <Calendar className="h-4 w-4 mr-2" />
              Fixtures
            </TabsTrigger>
            <TabsTrigger value="attendance" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-800" data-testid="tab-attendance">
              <Users className="h-4 w-4 mr-2" />
              Attendance
            </TabsTrigger>
            <TabsTrigger value="revenue" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-800" data-testid="tab-revenue">
              <DollarSign className="h-4 w-4 mr-2" />
              Revenue
            </TabsTrigger>
            <TabsTrigger value="scorers" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-800" data-testid="tab-scorers">
              <Trophy className="h-4 w-4 mr-2" />
              Top Performers
            </TabsTrigger>
          </TabsList>

          <TabsContent value="fixtures" className="space-y-4">
            <div className="flex justify-end">
              <Button onClick={() => handleExport('fixtures')} variant="outline" data-testid="button-export-fixtures">
                <Download className="h-4 w-4 mr-2" />
                Export CSV
              </Button>
            </div>

            {fixturesLoading ? (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardContent className="pt-6">
                  <p className="text-center text-gray-600 dark:text-gray-400">Loading fixtures data...</p>
                </CardContent>
              </Card>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Fixtures</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-gray-900 dark:text-gray-100" data-testid="text-total-fixtures">
                        {fixturesData?.total || 0}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Completed</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-green-600 dark:text-green-400" data-testid="text-completed-fixtures">
                        {fixturesData?.completed || 0}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Upcoming</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-blue-600 dark:text-blue-400" data-testid="text-upcoming-fixtures">
                        {fixturesData?.upcoming || 0}
                      </p>
                    </CardContent>
                  </Card>
                </div>

                {fixturesData?.byMonth && fixturesData.byMonth.length > 0 && (
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-gray-900 dark:text-gray-100">Fixtures by Month</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ResponsiveContainer width="100%" height={300}>
                        <BarChart data={fixturesData.byMonth}>
                          <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
                          <XAxis dataKey="month" stroke="#6B7280" />
                          <YAxis stroke="#6B7280" />
                          <Tooltip 
                            contentStyle={{ 
                              backgroundColor: '#1F2937', 
                              border: '1px solid #374151',
                              color: '#F3F4F6'
                            }} 
                          />
                          <Bar dataKey="count" fill="#3B82F6" />
                        </BarChart>
                      </ResponsiveContainer>
                    </CardContent>
                  </Card>
                )}
              </>
            )}
          </TabsContent>

          <TabsContent value="attendance" className="space-y-4">
            <div className="flex justify-end">
              <Button onClick={() => handleExport('attendance')} variant="outline" data-testid="button-export-attendance">
                <Download className="h-4 w-4 mr-2" />
                Export CSV
              </Button>
            </div>

            {attendanceLoading ? (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardContent className="pt-6">
                  <p className="text-center text-gray-600 dark:text-gray-400">Loading attendance data...</p>
                </CardContent>
              </Card>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Sessions</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-gray-900 dark:text-gray-100" data-testid="text-total-sessions">
                        {attendanceData?.totalSessions || 0}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Average Rate</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-green-600 dark:text-green-400" data-testid="text-average-rate">
                        {attendanceData?.averageAttendanceRate || 0}%
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Attendance</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-blue-600 dark:text-blue-400" data-testid="text-total-attendance">
                        {attendanceData?.totalAttendance || 0}
                      </p>
                    </CardContent>
                  </Card>
                </div>

                {attendanceData?.topAttenders && attendanceData.topAttenders.length > 0 && (
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-gray-900 dark:text-gray-100">Top Attenders</CardTitle>
                      <CardDescription className="text-gray-600 dark:text-gray-400">
                        Players with the best attendance records
                      </CardDescription>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        {attendanceData.topAttenders.map((player, index) => (
                          <div
                            key={player.playerId}
                            className="flex items-center justify-between p-3 rounded-lg bg-gray-50 dark:bg-gray-900"
                            data-testid={`card-top-attender-${player.playerId}`}
                          >
                            <div className="flex items-center gap-3">
                              <Badge variant={index < 3 ? "default" : "secondary"} className="w-8 h-8 flex items-center justify-center">
                                {index + 1}
                              </Badge>
                              <div>
                                <p className="font-medium text-gray-900 dark:text-gray-100">{player.playerName}</p>
                                <p className="text-sm text-gray-600 dark:text-gray-400">
                                  {player.sessionsAttended} sessions
                                </p>
                              </div>
                            </div>
                            <Badge variant="outline" className="text-green-700 dark:text-green-400 border-green-600 dark:border-green-700">
                              {player.attendanceRate}%
                            </Badge>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                )}
              </>
            )}
          </TabsContent>

          <TabsContent value="revenue" className="space-y-4">
            <div className="flex justify-end">
              <Button onClick={() => handleExport('revenue')} variant="outline" data-testid="button-export-revenue">
                <Download className="h-4 w-4 mr-2" />
                Export CSV
              </Button>
            </div>

            {revenueLoading ? (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardContent className="pt-6">
                  <p className="text-center text-gray-600 dark:text-gray-400">Loading revenue data...</p>
                </CardContent>
              </Card>
            ) : (
              <>
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Total Revenue</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-green-600 dark:text-green-400" data-testid="text-total-revenue">
                        ${revenueData?.totalRevenue.toFixed(2) || "0.00"}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Outstanding</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-red-600 dark:text-red-400" data-testid="text-outstanding-revenue">
                        ${revenueData?.outstandingPayments.toFixed(2) || "0.00"}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Paid</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-gray-900 dark:text-gray-100" data-testid="text-paid-count">
                        {revenueData?.paidCount || 0}
                      </p>
                    </CardContent>
                  </Card>
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-sm font-medium text-gray-600 dark:text-gray-400">Pending</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="text-3xl font-bold text-gray-900 dark:text-gray-100" data-testid="text-pending-count">
                        {revenueData?.pendingCount || 0}
                      </p>
                    </CardContent>
                  </Card>
                </div>

                {revenueData?.byMonth && revenueData.byMonth.length > 0 && (
                  <Card className="border-gray-200 dark:border-gray-800">
                    <CardHeader>
                      <CardTitle className="text-gray-900 dark:text-gray-100">Revenue by Month</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ResponsiveContainer width="100%" height={300}>
                        <LineChart data={revenueData.byMonth}>
                          <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
                          <XAxis dataKey="month" stroke="#6B7280" />
                          <YAxis stroke="#6B7280" />
                          <Tooltip 
                            contentStyle={{ 
                              backgroundColor: '#1F2937', 
                              border: '1px solid #374151',
                              color: '#F3F4F6'
                            }} 
                          />
                          <Line type="monotone" dataKey="amount" stroke="#10B981" strokeWidth={2} />
                        </LineChart>
                      </ResponsiveContainer>
                    </CardContent>
                  </Card>
                )}
              </>
            )}
          </TabsContent>

          <TabsContent value="scorers" className="space-y-4">
            <div className="flex justify-end">
              <Button onClick={() => handleExport('top-scorers')} variant="outline" data-testid="button-export-scorers">
                <Download className="h-4 w-4 mr-2" />
                Export CSV
              </Button>
            </div>

            {topScorersLoading ? (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardContent className="pt-6">
                  <p className="text-center text-gray-600 dark:text-gray-400">Loading top performers data...</p>
                </CardContent>
              </Card>
            ) : topScorersData?.topPlayers && topScorersData.topPlayers.length > 0 ? (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardHeader>
                  <CardTitle className="text-gray-900 dark:text-gray-100">Top Performers</CardTitle>
                  <CardDescription className="text-gray-600 dark:text-gray-400">
                    Players ranked by attendance and participation
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    {topScorersData.topPlayers.map((player, index) => (
                      <div
                        key={player.playerId}
                        className="flex items-center justify-between p-4 rounded-lg bg-gray-50 dark:bg-gray-900"
                        data-testid={`card-top-performer-${player.playerId}`}
                      >
                        <div className="flex items-center gap-4">
                          <Badge 
                            variant={index < 3 ? "default" : "secondary"} 
                            className="w-10 h-10 flex items-center justify-center text-lg"
                          >
                            {index + 1}
                          </Badge>
                          <div>
                            <p className="font-semibold text-gray-900 dark:text-gray-100">{player.playerName}</p>
                            <div className="flex items-center gap-2 mt-1">
                              <Badge variant="outline" className="text-xs">{player.position}</Badge>
                              <Badge variant="outline" className="text-xs">{player.teamName}</Badge>
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="text-sm text-gray-600 dark:text-gray-400">
                            {player.stats.matches} matches
                          </p>
                          <p className="text-lg font-bold text-green-600 dark:text-green-400">
                            {player.stats.attendanceRate}%
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            ) : (
              <Card className="border-gray-200 dark:border-gray-800">
                <CardContent className="pt-16 pb-16">
                  <div className="text-center">
                    <Trophy className="h-16 w-16 mx-auto mb-4 text-gray-300 dark:text-gray-700" />
                    <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                      No performance data yet
                    </h3>
                    <p className="text-gray-600 dark:text-gray-400">
                      Performance data will appear when players participate in matches and training sessions
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}
