import React, { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { format } from "date-fns";
import AttendanceReports from "@/components/attendance/attendance-reports";
import { 
  Calendar as CalendarIcon, 
  Clock, 
  Users, 
  CheckCircle, 
  XCircle, 
  AlertCircle,
  Plus,
  Eye,
  BarChart3,
  MapPin,
  Bell
} from "lucide-react";

interface AttendanceSession {
  id: number;
  title: string;
  description?: string;
  type: 'training' | 'match' | 'meeting' | 'event';
  date: string;
  startTime: string;
  endTime: string;
  location?: string;
  teamId?: number;
  coachId?: number;
  organizationId: number;
  isActive: boolean;
  attendanceRequired: boolean;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
}

interface AttendanceRecord {
  id: number;
  sessionId: number;
  playerId: number;
  status: 'present' | 'absent' | 'late' | 'excused';
  arrivalTime?: string;
  notes?: string;
  markedBy: string;
  markedAt: string;
}

interface Player {
  id: number;
  firstName: string;
  lastName: string;
  email?: string;
  phoneNumber?: string;
}

export default function Attendance() {
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [selectedSession, setSelectedSession] = useState<AttendanceSession | null>(null);
  const [showRecordsDialog, setShowRecordsDialog] = useState(false);
  const { toast } = useToast();
  const queryClient = useQueryClient();

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

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

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

  // Create session mutation
  const createSessionMutation = useMutation({
    mutationFn: async (sessionData: any) => {
      await apiRequest("POST", "/api/attendance/sessions", sessionData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/attendance/sessions"] });
      setShowCreateDialog(false);
      toast({
        title: "Session Created",
        description: "Attendance session has been created successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create attendance session",
        variant: "destructive",
      });
    },
  });

  // Fetch attendance records for a session
  const { data: attendanceRecords = [] } = useQuery({
    queryKey: ["/api/attendance/records", selectedSession?.id],
    enabled: !!selectedSession,
  });

  // Mark attendance mutation
  const markAttendanceMutation = useMutation({
    mutationFn: async (recordData: any) => {
      await apiRequest("POST", "/api/attendance/records", recordData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/attendance/records", selectedSession?.id] });
      toast({
        title: "Attendance Marked",
        description: "Player attendance has been recorded",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to mark attendance",
        variant: "destructive",
      });
    },
  });

  // Get today's sessions
  const todaySessions = sessions.filter((session: AttendanceSession) => 
    session.date === format(new Date(), "yyyy-MM-dd")
  );

  // Get upcoming sessions
  const upcomingSessions = sessions.filter((session: AttendanceSession) => 
    new Date(session.date) > new Date()
  ).slice(0, 5);

  const handleCreateSession = (formData: FormData) => {
    const sessionData = {
      title: formData.get("title"),
      description: formData.get("description"),
      type: formData.get("type"),
      date: format(selectedDate, "yyyy-MM-dd"),
      startTime: formData.get("startTime"),
      endTime: formData.get("endTime"),
      location: formData.get("location"),
      teamId: formData.get("teamId") ? parseInt(formData.get("teamId") as string) : null,
      organizationId: 1, // This should come from user context
      attendanceRequired: true,
    };

    createSessionMutation.mutate(sessionData);
  };

  const handleMarkAttendance = (playerId: number, status: string) => {
    if (!selectedSession) return;

    const recordData = {
      sessionId: selectedSession.id,
      playerId,
      status,
      arrivalTime: status === 'present' || status === 'late' ? format(new Date(), "HH:mm") : null,
    };

    markAttendanceMutation.mutate(recordData);
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      present: { variant: "default" as const, icon: CheckCircle, color: "text-green-600" },
      absent: { variant: "destructive" as const, icon: XCircle, color: "text-red-600" },
      late: { variant: "secondary" as const, icon: AlertCircle, color: "text-yellow-600" },
      excused: { variant: "outline" as const, icon: CheckCircle, color: "text-blue-600" },
    };

    const config = variants[status as keyof typeof variants] || variants.absent;
    const Icon = config.icon;

    return (
      <Badge variant={config.variant} className="flex items-center gap-1">
        <Icon className="h-3 w-3" />
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </Badge>
    );
  };

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Attendance Tracking</h1>
          <p className="text-gray-600">Manage training sessions and track player attendance</p>
        </div>
        
        <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Create Session
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create Attendance Session</DialogTitle>
              <DialogDescription>
                Schedule a new training session, match, or meeting
              </DialogDescription>
            </DialogHeader>
            
            <div className="max-h-[60vh] overflow-y-auto">
              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                handleCreateSession(formData);
              }} className="space-y-6 p-1">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="title">Session Title</Label>
                    <Input name="title" placeholder="e.g., Team Training Session" required />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="type">Session Type</Label>
                    <Select name="type" required>
                      <SelectTrigger>
                        <SelectValue placeholder="Select session type" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="training">Training</SelectItem>
                        <SelectItem value="match">Match</SelectItem>
                        <SelectItem value="meeting">Meeting</SelectItem>
                        <SelectItem value="event">Event</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="date">Date</Label>
                    <Popover>
                      <PopoverTrigger asChild>
                        <Button variant="outline" className="w-full justify-start text-left font-normal">
                          <CalendarIcon className="mr-2 h-4 w-4" />
                          {format(selectedDate, "MMM d, yyyy")}
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-auto p-0">
                        <Calendar
                          mode="single"
                          selected={selectedDate}
                          onSelect={(date) => date && setSelectedDate(date)}
                          initialFocus
                        />
                      </PopoverContent>
                    </Popover>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="startTime">Start Time</Label>
                    <Input name="startTime" type="time" required />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="endTime">End Time</Label>
                    <Input name="endTime" type="time" required />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="location">Location</Label>
                    <Input name="location" placeholder="Training ground, stadium, etc." />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="teamId">Team (Optional)</Label>
                    <Select name="teamId">
                      <SelectTrigger>
                        <SelectValue placeholder="Select team" />
                      </SelectTrigger>
                      <SelectContent>
                        {teams && Array.isArray(teams) && teams.map((team: any) => (
                          <SelectItem key={team.id} value={team.id.toString()}>
                            {team.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">Description (Optional)</Label>
                  <Textarea 
                    name="description" 
                    placeholder="Additional details about the session" 
                    rows={3}
                  />
                </div>

                <Button type="submit" className="w-full" disabled={createSessionMutation.isPending}>
                  {createSessionMutation.isPending ? "Creating..." : "Create Session"}
                </Button>
              </form>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Tabs defaultValue="sessions" className="space-y-6">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="sessions">Sessions</TabsTrigger>
          <TabsTrigger value="reports">Reports</TabsTrigger>
          <TabsTrigger value="analytics">Analytics</TabsTrigger>
          <TabsTrigger value="notifications">Notifications</TabsTrigger>
        </TabsList>

        <TabsContent value="sessions" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Today's Sessions */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="h-5 w-5" />
              Today's Sessions
            </CardTitle>
            <CardDescription>
              {format(new Date(), "EEEE, MMMM d, yyyy")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {todaySessions.length === 0 ? (
              <p className="text-gray-500 text-center py-8">No sessions scheduled for today</p>
            ) : (
              <div className="space-y-4">
                {todaySessions.map((session: AttendanceSession) => (
                  <div key={session.id} className="flex items-center justify-between p-4 border rounded-lg">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="font-medium">{session.title}</h3>
                        <Badge variant="outline">{session.type}</Badge>
                      </div>
                      <div className="flex items-center gap-4 text-sm text-gray-600">
                        <span className="flex items-center gap-1">
                          <Clock className="h-3 w-3" />
                          {session.startTime} - {session.endTime}
                        </span>
                        {session.location && (
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {session.location}
                          </span>
                        )}
                      </div>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setSelectedSession(session);
                        setShowRecordsDialog(true);
                      }}
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      Mark Attendance
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Upcoming Sessions */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CalendarIcon className="h-5 w-5" />
              Upcoming Sessions
            </CardTitle>
          </CardHeader>
          <CardContent>
            {upcomingSessions.length === 0 ? (
              <p className="text-gray-500 text-sm">No upcoming sessions</p>
            ) : (
              <div className="space-y-3">
                {upcomingSessions.map((session: AttendanceSession) => (
                  <div key={session.id} className="p-3 border rounded-lg">
                    <h4 className="font-medium text-sm">{session.title}</h4>
                    <div className="flex items-center gap-2 mt-1 text-xs text-gray-600">
                      <span>{format(new Date(session.date), "MMM d")}</span>
                      <span>•</span>
                      <span>{session.startTime}</span>
                      <Badge variant="outline" className="text-xs">{session.type}</Badge>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
          </div>
        </TabsContent>

        <TabsContent value="reports" className="space-y-6">
          <AttendanceReports />
        </TabsContent>

        <TabsContent value="analytics" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <BarChart3 className="h-5 w-5" />
                Attendance Analytics
              </CardTitle>
              <CardDescription>
                Real-time attendance insights and team performance metrics
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8">
                <BarChart3 className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">Advanced analytics dashboard with attendance trends and performance insights</p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="notifications" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Bell className="h-5 w-5" />
                Notification Center
              </CardTitle>
              <CardDescription>
                Manage automated attendance notifications and alerts
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div>
                    <h4 className="font-medium">Session Reminders</h4>
                    <p className="text-sm text-gray-600">Send reminders 24 hours before sessions</p>
                  </div>
                  <Button variant="outline" size="sm">
                    Configure
                  </Button>
                </div>
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div>
                    <h4 className="font-medium">Absence Alerts</h4>
                    <p className="text-sm text-gray-600">Alert coaches when players miss multiple sessions</p>
                  </div>
                  <Button variant="outline" size="sm">
                    Configure
                  </Button>
                </div>
                <div className="flex items-center justify-between p-4 border rounded-lg">
                  <div>
                    <h4 className="font-medium">Late Arrival Notifications</h4>
                    <p className="text-sm text-gray-600">Track and notify about frequent late arrivals</p>
                  </div>
                  <Button variant="outline" size="sm">
                    Configure
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Attendance Marking Dialog */}
      <Dialog open={showRecordsDialog} onOpenChange={setShowRecordsDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Mark Attendance - {selectedSession?.title}</DialogTitle>
            <DialogDescription>
              {selectedSession && format(new Date(selectedSession.date), "EEEE, MMMM d, yyyy")} • {selectedSession?.startTime} - {selectedSession?.endTime}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 max-h-96 overflow-y-auto">
            {players.map((player: Player) => {
              const existingRecord = attendanceRecords.find((record: AttendanceRecord) => 
                record.playerId === player.id
              );

              return (
                <div key={player.id} className="flex items-center justify-between p-3 border rounded-lg">
                  <div>
                    <h4 className="font-medium">{player.firstName} {player.lastName}</h4>
                    {player.email && (
                      <p className="text-sm text-gray-600">{player.email}</p>
                    )}
                  </div>
                  
                  <div className="flex items-center gap-2">
                    {existingRecord ? (
                      getStatusBadge(existingRecord.status)
                    ) : (
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-green-600 border-green-600"
                          onClick={() => handleMarkAttendance(player.id, 'present')}
                        >
                          <CheckCircle className="h-3 w-3 mr-1" />
                          Present
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-yellow-600 border-yellow-600"
                          onClick={() => handleMarkAttendance(player.id, 'late')}
                        >
                          <AlertCircle className="h-3 w-3 mr-1" />
                          Late
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-red-600 border-red-600"
                          onClick={() => handleMarkAttendance(player.id, 'absent')}
                        >
                          <XCircle className="h-3 w-3 mr-1" />
                          Absent
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}