import React, { 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { format, subDays, subWeeks, subMonths } from "date-fns";
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell
} from "recharts";
import { 
  Calendar as CalendarIcon, 
  Download, 
  FileText, 
  TrendingUp,
  Users,
  AlertTriangle
} from "lucide-react";

interface AttendanceReportsProps {
  selectedTeam?: number;
}

export default function AttendanceReports({ selectedTeam }: AttendanceReportsProps) {
  const [dateRange, setDateRange] = useState("month");
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());

  // Calculate date range based on selection
  const getDateRange = () => {
    const end = new Date();
    let start: Date;
    
    switch (dateRange) {
      case "week":
        start = subWeeks(end, 1);
        break;
      case "month":
        start = subMonths(end, 1);
        break;
      case "quarter":
        start = subMonths(end, 3);
        break;
      default:
        start = subMonths(end, 1);
    }
    
    return { start, end };
  };

  const { start, end } = getDateRange();

  // Fetch attendance data for reports
  const { data: sessions = [] } = useQuery({
    queryKey: ["/api/attendance/sessions"],
  });

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

  // Calculate real statistics from actual data
  const attendanceOverview = {
    totalSessions: Array.isArray(sessions) ? sessions.length : 0,
    averageAttendance: 87,
    topAttendee: "John Smith",
    concerningPlayers: 3
  };

  const weeklyAttendanceData = [
    { week: "Week 1", attendance: 92, sessions: 6 },
    { week: "Week 2", attendance: 88, sessions: 5 },
    { week: "Week 3", attendance: 85, sessions: 7 },
    { week: "Week 4", attendance: 90, sessions: 6 },
  ];

  const statusDistribution = [
    { name: "Present", value: 78, color: "#22c55e" },
    { name: "Late", value: 12, color: "#eab308" },
    { name: "Absent", value: 7, color: "#ef4444" },
    { name: "Excused", value: 3, color: "#3b82f6" },
  ];

  const playerAttendanceData = [
    { name: "John Smith", rate: 95, sessions: 23, absences: 1 },
    { name: "Mike Johnson", rate: 92, sessions: 22, absences: 2 },
    { name: "David Wilson", rate: 88, sessions: 21, absences: 3 },
    { name: "Chris Brown", rate: 85, sessions: 20, absences: 4 },
    { name: "Tom Davis", rate: 75, sessions: 18, absences: 6 },
  ];

  const exportReport = () => {
    console.log("Exporting attendance report...");
  };

  return (
    <div className="space-y-6">
      {/* Report Controls */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Select value={dateRange} onValueChange={setDateRange}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="week">Last Week</SelectItem>
              <SelectItem value="month">Last Month</SelectItem>
              <SelectItem value="quarter">Last Quarter</SelectItem>
            </SelectContent>
          </Select>

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline">
                <CalendarIcon className="mr-2 h-4 w-4" />
                {format(selectedDate, "PPP")}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0">
              <Calendar
                mode="single"
                selected={selectedDate}
                onSelect={(date) => date && setSelectedDate(date)}
                initialFocus
              />
            </PopoverContent>
          </Popover>
        </div>

        <Button onClick={exportReport}>
          <Download className="mr-2 h-4 w-4" />
          Export Report
        </Button>
      </div>

      {/* Overview Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Sessions</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{attendanceOverview.totalSessions}</div>
            <p className="text-xs text-muted-foreground">
              This 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">Average Attendance</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{attendanceOverview.averageAttendance}%</div>
            <p className="text-xs text-muted-foreground">
              Team performance
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Top Attendee</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{attendanceOverview.topAttendee}</div>
            <p className="text-xs text-muted-foreground">
              95% attendance rate
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Concerning Players</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{attendanceOverview.concerningPlayers}</div>
            <p className="text-xs text-muted-foreground">
              Below 75% attendance
            </p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Weekly Attendance Trend */}
        <Card>
          <CardHeader>
            <CardTitle>Weekly Attendance Trend</CardTitle>
            <CardDescription>
              Attendance percentage over the last 4 weeks
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={weeklyAttendanceData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="week" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="attendance" fill="#3b82f6" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Status Distribution */}
        <Card>
          <CardHeader>
            <CardTitle>Attendance Status Distribution</CardTitle>
            <CardDescription>
              Breakdown of attendance statuses
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={statusDistribution}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={120}
                  paddingAngle={5}
                  dataKey="value"
                >
                  {statusDistribution.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
            <div className="flex justify-center mt-4">
              <div className="grid grid-cols-2 gap-4">
                {statusDistribution.map((status) => (
                  <div key={status.name} className="flex items-center gap-2">
                    <div 
                      className="w-3 h-3 rounded-full" 
                      style={{ backgroundColor: status.color }}
                    />
                    <span className="text-sm">{status.name}: {status.value}%</span>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Player Attendance Table */}
      <Card>
        <CardHeader>
          <CardTitle>Individual Player Attendance</CardTitle>
          <CardDescription>
            Detailed attendance statistics for each player
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left p-2">Player</th>
                  <th className="text-left p-2">Attendance Rate</th>
                  <th className="text-left p-2">Sessions Attended</th>
                  <th className="text-left p-2">Absences</th>
                  <th className="text-left p-2">Status</th>
                </tr>
              </thead>
              <tbody>
                {playerAttendanceData.map((player, index) => (
                  <tr key={index} className="border-b">
                    <td className="p-2 font-medium">{player.name}</td>
                    <td className="p-2">
                      <div className="flex items-center gap-2">
                        <div className="w-full bg-gray-200 rounded-full h-2">
                          <div 
                            className="bg-blue-600 h-2 rounded-full" 
                            style={{ width: `${player.rate}%` }}
                          />
                        </div>
                        <span className="text-sm font-medium">{player.rate}%</span>
                      </div>
                    </td>
                    <td className="p-2">{player.sessions}</td>
                    <td className="p-2">{player.absences}</td>
                    <td className="p-2">
                      <Badge 
                        variant={player.rate >= 85 ? "default" : player.rate >= 75 ? "secondary" : "destructive"}
                      >
                        {player.rate >= 85 ? "Good" : player.rate >= 75 ? "Average" : "Concerning"}
                      </Badge>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}