import { 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 { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import {
  Calendar,
  Clock,
  MapPin,
  Users,
  Plus,
  Edit,
  Target,
  Zap,
  Activity,
  CheckCircle,
  XCircle,
  Timer,
  Dumbbell
} from "lucide-react";

interface TrainingSession {
  id: number;
  title: string;
  description: string;
  date: string;
  startTime: string;
  endTime: string;
  location: string;
  type: "fitness" | "technical" | "tactical" | "recovery" | "scrimmage";
  intensity: "low" | "medium" | "high";
  status: "scheduled" | "ongoing" | "completed" | "cancelled";
  teamId: number;
  teamName: string;
  coachId: number;
  coachName: string;
  attendees: number;
  maxAttendees: number;
  equipment: string[];
  objectives: string[];
}

interface TrainingPlan {
  id: number;
  name: string;
  description: string;
  startDate: string;
  endDate: string;
  teamId: number;
  teamName: string;
  coachId: number;
  coachName: string;
  sessions: number;
  completedSessions: number;
  focus: string[];
  status: "draft" | "active" | "completed";
}

export default function Training() {
  const [selectedWeek, setSelectedWeek] = useState(new Date());
  const [selectedType, setSelectedType] = useState("");
  const [selectedTeam, setSelectedTeam] = useState("");
  const [showCreateSession, setShowCreateSession] = useState(false);
  const [showCreatePlan, setShowCreatePlan] = useState(false);
  const [selectedSession, setSelectedSession] = useState<TrainingSession | null>(null);
  const { toast } = useToast();
  const queryClient = useQueryClient();

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

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

  // Mock training sessions data
  const { data: trainingSessions = [], isLoading } = useQuery({
    queryKey: ["/api/training/sessions"],
    queryFn: async () => {
      return [
        {
          id: 1,
          title: "Morning Fitness Training",
          description: "Cardio and strength conditioning session",
          date: "2024-12-28",
          startTime: "08:00",
          endTime: "10:00",
          location: "Training Ground A",
          type: "fitness",
          intensity: "high",
          status: "scheduled",
          teamId: 10,
          teamName: "Barewa",
          coachId: 1,
          coachName: "Coach Smith",
          attendees: 18,
          maxAttendees: 20,
          equipment: ["Cones", "Resistance bands", "Medicine balls"],
          objectives: ["Improve cardiovascular endurance", "Build core strength"]
        },
        {
          id: 2,
          title: "Technical Skills Workshop",
          description: "Ball control and passing drills",
          date: "2024-12-28",
          startTime: "15:00",
          endTime: "17:00",
          location: "Training Ground B",
          type: "technical",
          intensity: "medium",
          status: "completed",
          teamId: 11,
          teamName: "Lagos Stars",
          coachId: 2,
          coachName: "Coach Johnson",
          attendees: 22,
          maxAttendees: 25,
          equipment: ["Footballs", "Cones", "Agility ladder"],
          objectives: ["Improve first touch", "Enhance passing accuracy"]
        },
        {
          id: 3,
          title: "Tactical Formation Practice",
          description: "4-3-3 formation drills and positioning",
          date: "2024-12-29",
          startTime: "10:00",
          endTime: "12:00",
          location: "Main Pitch",
          type: "tactical",
          intensity: "medium",
          status: "scheduled",
          teamId: 10,
          teamName: "Barewa",
          coachId: 1,
          coachName: "Coach Smith",
          attendees: 0,
          maxAttendees: 20,
          equipment: ["Cones", "Bibs", "Tactical board"],
          objectives: ["Master 4-3-3 formation", "Improve team coordination"]
        }
      ];
    },
  });

  // Mock training plans data
  const { data: trainingPlans = [] } = useQuery({
    queryKey: ["/api/training/plans"],
    queryFn: async () => {
      return [
        {
          id: 1,
          name: "Pre-Season Preparation",
          description: "Comprehensive fitness and skill development program",
          startDate: "2024-12-01",
          endDate: "2025-01-15",
          teamId: 10,
          teamName: "Barewa",
          coachId: 1,
          coachName: "Coach Smith",
          sessions: 24,
          completedSessions: 18,
          focus: ["Fitness", "Ball Skills", "Team Tactics"],
          status: "active"
        },
        {
          id: 2,
          name: "Mid-Season Maintenance",
          description: "Maintain fitness levels during competitive season",
          startDate: "2025-01-15",
          endDate: "2025-04-30",
          teamId: 11,
          teamName: "Lagos Stars",
          coachId: 2,
          coachName: "Coach Johnson",
          sessions: 36,
          completedSessions: 0,
          focus: ["Technical Skills", "Match Preparation"],
          status: "draft"
        }
      ];
    },
  });

  const createSessionMutation = useMutation({
    mutationFn: async (data: any) => {
      await apiRequest("POST", "/api/training/sessions", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/training/sessions"] });
      toast({
        title: "Success",
        description: "Training session created successfully",
      });
      setShowCreateSession(false);
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to create training session",
        variant: "destructive",
      });
    },
  });

  const filteredSessions = trainingSessions.filter(session => {
    const typeMatch = selectedType ? session.type === selectedType : true;
    const teamMatch = selectedTeam ? session.teamId.toString() === selectedTeam : true;
    return typeMatch && teamMatch;
  });

  const getTypeColor = (type: string) => {
    switch (type) {
      case "fitness": return "bg-red-500";
      case "technical": return "bg-blue-500";
      case "tactical": return "bg-green-500";
      case "recovery": return "bg-purple-500";
      case "scrimmage": return "bg-orange-500";
      default: return "bg-gray-500";
    }
  };

  const getIntensityColor = (intensity: string) => {
    switch (intensity) {
      case "low": return "bg-green-500";
      case "medium": return "bg-yellow-500";
      case "high": return "bg-red-500";
      default: return "bg-gray-500";
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "scheduled": return "bg-blue-500";
      case "ongoing": return "bg-yellow-500";
      case "completed": return "bg-green-500";
      case "cancelled": return "bg-red-500";
      default: return "bg-gray-500";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "scheduled": return <Clock className="h-4 w-4" />;
      case "ongoing": return <Activity className="h-4 w-4" />;
      case "completed": return <CheckCircle className="h-4 w-4" />;
      case "cancelled": return <XCircle className="h-4 w-4" />;
      default: return <Clock className="h-4 w-4" />;
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "fitness": return <Dumbbell className="h-4 w-4" />;
      case "technical": return <Target className="h-4 w-4" />;
      case "tactical": return <Users className="h-4 w-4" />;
      case "recovery": return <Timer className="h-4 w-4" />;
      case "scrimmage": return <Zap className="h-4 w-4" />;
      default: return <Activity className="h-4 w-4" />;
    }
  };

  const todaySessions = trainingSessions.filter(session => 
    session.date === new Date().toISOString().split('T')[0]
  );

  const upcomingSessions = trainingSessions.filter(session => 
    new Date(session.date) > new Date() && session.status === "scheduled"
  ).slice(0, 5);

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Training Management</h1>
          <p className="text-gray-600">Schedule and manage team training sessions and programs</p>
        </div>
        <div className="flex space-x-3">
          <Button onClick={() => setShowCreatePlan(true)} variant="outline">
            <Calendar className="h-4 w-4 mr-2" />
            Create Plan
          </Button>
          <Button onClick={() => setShowCreateSession(true)}>
            <Plus className="h-4 w-4 mr-2" />
            Schedule Session
          </Button>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Today's Sessions</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <Activity className="h-8 w-8 text-blue-500" />
              <span className="text-3xl font-bold">{todaySessions.length}</span>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">This Week</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <Calendar className="h-8 w-8 text-green-500" />
              <span className="text-3xl font-bold">12</span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Active Plans</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <Target className="h-8 w-8 text-purple-500" />
              <span className="text-3xl font-bold">
                {trainingPlans.filter(p => p.status === "active").length}
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-gray-600">Completion Rate</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-2">
              <CheckCircle className="h-8 w-8 text-yellow-500" />
              <span className="text-3xl font-bold">87%</span>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs defaultValue="sessions" className="space-y-6">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="sessions">Training Sessions</TabsTrigger>
          <TabsTrigger value="plans">Training Plans</TabsTrigger>
          <TabsTrigger value="calendar">Calendar View</TabsTrigger>
        </TabsList>

        <TabsContent value="sessions" className="space-y-6">
          {/* Filters */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center">
                <Activity className="h-5 w-5 mr-2" />
                Session Filters
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <Label htmlFor="type-filter">Type</Label>
                  <Select value={selectedType} onValueChange={setSelectedType}>
                    <SelectTrigger>
                      <SelectValue placeholder="All types" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All types</SelectItem>
                      <SelectItem value="fitness">Fitness</SelectItem>
                      <SelectItem value="technical">Technical</SelectItem>
                      <SelectItem value="tactical">Tactical</SelectItem>
                      <SelectItem value="recovery">Recovery</SelectItem>
                      <SelectItem value="scrimmage">Scrimmage</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="team-filter">Team</Label>
                  <Select value={selectedTeam} onValueChange={setSelectedTeam}>
                    <SelectTrigger>
                      <SelectValue placeholder="All teams" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All teams</SelectItem>
                      {(teams as any[]).map((team: any) => (
                        <SelectItem key={team.id} value={team.id.toString()}>
                          {team.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex items-end">
                  <Button variant="outline" onClick={() => {
                    setSelectedType("");
                    setSelectedTeam("");
                  }}>
                    Clear Filters
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Today's Sessions */}
          {todaySessions.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center">
                  <Clock className="h-5 w-5 mr-2" />
                  Today's Sessions
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  {todaySessions.map((session) => (
                    <div key={session.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <h3 className="font-medium">{session.title}</h3>
                        <div className="flex space-x-2">
                          <Badge className={getTypeColor(session.type)}>
                            {getTypeIcon(session.type)}
                            <span className="ml-1">{session.type}</span>
                          </Badge>
                          <Badge className={getStatusColor(session.status)}>
                            {getStatusIcon(session.status)}
                            <span className="ml-1">{session.status}</span>
                          </Badge>
                        </div>
                      </div>
                      <div className="text-sm text-gray-600 space-y-1">
                        <p className="flex items-center">
                          <Clock className="h-4 w-4 mr-2" />
                          {session.startTime} - {session.endTime}
                        </p>
                        <p className="flex items-center">
                          <MapPin className="h-4 w-4 mr-2" />
                          {session.location}
                        </p>
                        <p className="flex items-center">
                          <Users className="h-4 w-4 mr-2" />
                          {session.attendees}/{session.maxAttendees} attendees
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* All Sessions */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {filteredSessions.map((session) => (
              <Card key={session.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center">
                      {getTypeIcon(session.type)}
                      <span className="ml-2">{session.title}</span>
                    </CardTitle>
                    <div className="flex space-x-2">
                      <Badge className={getTypeColor(session.type)}>
                        {session.type}
                      </Badge>
                      <Badge className={getIntensityColor(session.intensity)}>
                        {session.intensity}
                      </Badge>
                      <Badge className={getStatusColor(session.status)}>
                        {getStatusIcon(session.status)}
                        <span className="ml-1">{session.status}</span>
                      </Badge>
                    </div>
                  </div>
                  <CardDescription>{session.description}</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex items-center text-gray-600">
                      <Calendar className="h-4 w-4 mr-2" />
                      {new Date(session.date).toLocaleDateString()}
                    </div>
                    <div className="flex items-center text-gray-600">
                      <Clock className="h-4 w-4 mr-2" />
                      {session.startTime} - {session.endTime}
                    </div>
                    <div className="flex items-center text-gray-600">
                      <MapPin className="h-4 w-4 mr-2" />
                      {session.location}
                    </div>
                    <div className="flex items-center text-gray-600">
                      <Users className="h-4 w-4 mr-2" />
                      {session.attendees}/{session.maxAttendees}
                    </div>
                  </div>

                  <div>
                    <p className="text-sm font-medium text-gray-700 mb-1">Objectives:</p>
                    <div className="flex flex-wrap gap-1">
                      {session.objectives.map((objective, index) => (
                        <Badge key={index} variant="outline" className="text-xs">
                          {objective}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  <div className="flex space-x-2">
                    <Button variant="outline" size="sm">
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </Button>
                    <Button variant="outline" size="sm">
                      View Details
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="plans" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {trainingPlans.map((plan) => (
              <Card key={plan.id}>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle>{plan.name}</CardTitle>
                    <Badge className={plan.status === "active" ? "bg-green-500" : plan.status === "draft" ? "bg-blue-500" : "bg-gray-500"}>
                      {plan.status}
                    </Badge>
                  </div>
                  <CardDescription>{plan.description}</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="flex items-center text-gray-600">
                      <Calendar className="h-4 w-4 mr-2" />
                      {new Date(plan.startDate).toLocaleDateString()} - {new Date(plan.endDate).toLocaleDateString()}
                    </div>
                    <div className="flex items-center text-gray-600">
                      <Users className="h-4 w-4 mr-2" />
                      {plan.teamName}
                    </div>
                  </div>

                  <div>
                    <div className="flex justify-between text-sm mb-2">
                      <span>Progress</span>
                      <span>{plan.completedSessions}/{plan.sessions} sessions</span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-primary h-2 rounded-full"
                        style={{ width: `${(plan.completedSessions / plan.sessions) * 100}%` }}
                      />
                    </div>
                  </div>

                  <div>
                    <p className="text-sm font-medium text-gray-700 mb-1">Focus Areas:</p>
                    <div className="flex flex-wrap gap-1">
                      {plan.focus.map((area, index) => (
                        <Badge key={index} variant="outline" className="text-xs">
                          {area}
                        </Badge>
                      ))}
                    </div>
                  </div>

                  <div className="flex space-x-2">
                    <Button variant="outline" size="sm">
                      <Edit className="h-4 w-4 mr-1" />
                      Edit Plan
                    </Button>
                    <Button variant="outline" size="sm">
                      View Sessions
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="calendar" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Training Calendar</CardTitle>
              <CardDescription>Visual calendar view of all training sessions</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8 text-gray-500">
                <Calendar className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                <p>Calendar view will be displayed here</p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Create Session Dialog */}
      <Dialog open={showCreateSession} onOpenChange={setShowCreateSession}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Schedule Training Session</DialogTitle>
            <DialogDescription>
              Create a new training session for your team
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="md:col-span-2">
              <Label htmlFor="title">Session Title</Label>
              <Input placeholder="Enter session title" />
            </div>
            <div className="md:col-span-2">
              <Label htmlFor="description">Description</Label>
              <Textarea placeholder="Session description and goals" />
            </div>
            <div>
              <Label htmlFor="date">Date</Label>
              <Input type="date" />
            </div>
            <div>
              <Label htmlFor="team">Team</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select team" />
                </SelectTrigger>
                <SelectContent>
                  {(teams as any[]).map((team: any) => (
                    <SelectItem key={team.id} value={team.id.toString()}>
                      {team.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="startTime">Start Time</Label>
              <Input type="time" />
            </div>
            <div>
              <Label htmlFor="endTime">End Time</Label>
              <Input type="time" />
            </div>
            <div>
              <Label htmlFor="location">Location</Label>
              <Input placeholder="Training venue" />
            </div>
            <div>
              <Label htmlFor="type">Type</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="fitness">Fitness</SelectItem>
                  <SelectItem value="technical">Technical</SelectItem>
                  <SelectItem value="tactical">Tactical</SelectItem>
                  <SelectItem value="recovery">Recovery</SelectItem>
                  <SelectItem value="scrimmage">Scrimmage</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="intensity">Intensity</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select intensity" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">Low</SelectItem>
                  <SelectItem value="medium">Medium</SelectItem>
                  <SelectItem value="high">High</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="maxAttendees">Max Attendees</Label>
              <Input type="number" placeholder="25" />
            </div>
            <div className="md:col-span-2 flex space-x-2">
              <Button onClick={() => setShowCreateSession(false)} variant="outline" className="flex-1">
                Cancel
              </Button>
              <Button className="flex-1">
                Schedule Session
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Create Plan Dialog */}
      <Dialog open={showCreatePlan} onOpenChange={setShowCreatePlan}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Create Training Plan</DialogTitle>
            <DialogDescription>
              Design a comprehensive training program for your team
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="md:col-span-2">
              <Label htmlFor="planName">Plan Name</Label>
              <Input placeholder="Enter plan name" />
            </div>
            <div className="md:col-span-2">
              <Label htmlFor="planDescription">Description</Label>
              <Textarea placeholder="Plan description and objectives" />
            </div>
            <div>
              <Label htmlFor="startDate">Start Date</Label>
              <Input type="date" />
            </div>
            <div>
              <Label htmlFor="endDate">End Date</Label>
              <Input type="date" />
            </div>
            <div>
              <Label htmlFor="planTeam">Team</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select team" />
                </SelectTrigger>
                <SelectContent>
                  {(teams as any[]).map((team: any) => (
                    <SelectItem key={team.id} value={team.id.toString()}>
                      {team.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="coach">Coach</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select coach" />
                </SelectTrigger>
                <SelectContent>
                  {(coaches as any[]).map((coach: any) => (
                    <SelectItem key={coach.id} value={coach.id.toString()}>
                      {coach.firstName} {coach.lastName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="totalSessions">Total Sessions</Label>
              <Input type="number" placeholder="24" />
            </div>
            <div className="md:col-span-2 flex space-x-2">
              <Button onClick={() => setShowCreatePlan(false)} variant="outline" className="flex-1">
                Cancel
              </Button>
              <Button className="flex-1">
                Create Plan
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}