import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Link } from "wouter";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import CoachForm from "@/components/forms/coach-form";
import { Plus, Edit, Trash2, UserCheck, Search, Mail, Phone, Eye, Users, X } from "lucide-react";
import type { Coach, Team, TeamCoach } from "@shared/schema";

export default function Coaches() {
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [selectedCoach, setSelectedCoach] = useState<Coach | null>(null);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showTeamAssignDialog, setShowTeamAssignDialog] = useState(false);
  const [coachForTeamAssignment, setCoachForTeamAssignment] = useState<Coach | null>(null);
  const [selectedTeamId, setSelectedTeamId] = useState<string>("");
  const [selectedRole, setSelectedRole] = useState<string>("assistant_coach");
  const { toast } = useToast();
  const queryClient = useQueryClient();

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

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

  const { data: coachTeams = [] } = useQuery<TeamCoach[]>({
    queryKey: coachForTeamAssignment ? [`/api/coaches/${coachForTeamAssignment.id}/teams`] : [],
    enabled: !!coachForTeamAssignment,
  });

  const deleteCoachMutation = useMutation({
    mutationFn: async (coachId: number) => {
      await apiRequest("DELETE", `/api/coaches/${coachId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/coaches"] });
      toast({
        title: "Success",
        description: "Coach deleted successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to delete coach",
        variant: "destructive",
      });
    },
  });

  const assignTeamMutation = useMutation({
    mutationFn: async ({ teamId, coachId, role }: { teamId: number; coachId: number; role: string }) => {
      await apiRequest("POST", `/api/teams/${teamId}/coaches`, { 
        coachId, 
        role,
        startDate: new Date().toISOString().split('T')[0]
      });
      return { coachId }; // Return coachId for use in onSuccess
    },
    onSuccess: (_data, variables) => {
      // Use coachId from mutation variables to ensure we invalidate the correct query
      queryClient.invalidateQueries({ queryKey: [`/api/coaches/${variables.coachId}/teams`] });
      setSelectedTeamId("");
      setSelectedRole("assistant_coach");
      toast({
        title: "Success",
        description: "Coach assigned to team successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to assign coach to team",
        variant: "destructive",
      });
    },
  });

  const removeTeamMutation = useMutation({
    mutationFn: async ({ teamId, coachId }: { teamId: number; coachId: number }) => {
      await apiRequest("DELETE", `/api/teams/${teamId}/coaches/${coachId}`);
      return { coachId }; // Return coachId for use in onSuccess
    },
    onSuccess: (_data, variables) => {
      // Use coachId from mutation variables to ensure we invalidate the correct query
      queryClient.invalidateQueries({ queryKey: [`/api/coaches/${variables.coachId}/teams`] });
      toast({
        title: "Success",
        description: "Coach removed from team successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to remove coach from team",
        variant: "destructive",
      });
    },
  });

  const filteredCoaches = (coaches as Coach[] || [])?.filter((coach: Coach) => {
    const matchesSearch = 
      `${coach.firstName} ${coach.lastName}`.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (coach.email || "").toLowerCase().includes(searchQuery.toLowerCase()) ||
      (coach.specialization || "").toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesStatus = statusFilter === "all" || coach.status === statusFilter;
    
    return matchesSearch && matchesStatus;
  }) || [];

  const handleEdit = (coach: Coach) => {
    setSelectedCoach(coach);
    setShowEditDialog(true);
  };

  const handleDelete = async (coachId: number) => {
    if (window.confirm("Are you sure you want to delete this coach?")) {
      deleteCoachMutation.mutate(coachId);
    }
  };

  const handleTeamAssignment = (coach: Coach) => {
    setCoachForTeamAssignment(coach);
    setShowTeamAssignDialog(true);
  };

  const handleAssignTeam = () => {
    if (!selectedTeamId || !coachForTeamAssignment) return;
    
    assignTeamMutation.mutate({
      teamId: parseInt(selectedTeamId),
      coachId: coachForTeamAssignment.id,
      role: selectedRole,
    });
  };

  const handleRemoveTeam = (teamId: number) => {
    if (!coachForTeamAssignment) return;
    
    if (window.confirm("Are you sure you want to remove this coach from the team?")) {
      removeTeamMutation.mutate({
        teamId,
        coachId: coachForTeamAssignment.id,
      });
    }
  };

  // Get teams that are not already assigned to the coach
  const availableTeams = teams.filter(
    (team) => !coachTeams.some((ct: any) => ct.teamId === team.id)
  );

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading coaches...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Beautiful Gradient Header */}
      <div className="relative bg-gradient-to-br from-blue-600 via-purple-600 to-blue-800 text-white overflow-hidden">
        {/* Background decorative elements */}
        <div className="absolute inset-0">
          <div className="absolute top-0 left-1/4 w-72 h-72 bg-white/10 rounded-full blur-3xl"></div>
          <div className="absolute bottom-0 right-1/4 w-96 h-96 bg-purple-300/20 rounded-full blur-3xl"></div>
          <div className="absolute top-1/2 left-3/4 w-64 h-64 bg-blue-300/10 rounded-full blur-2xl"></div>
        </div>
        
        {/* Header content */}
        <div className="relative z-10 px-6 py-12">
          <div className="max-w-7xl mx-auto">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center space-x-6">
                {/* Coaching Icon */}
                <div className="w-24 h-24 bg-white/20 backdrop-blur-sm rounded-full p-6 flex items-center justify-center">
                  <UserCheck className="w-12 h-12 text-white" />
                </div>

                <div className="flex-1">
                  <h1 className="text-4xl font-bold mb-2">Coaching Staff</h1>
                  <div className="flex items-center gap-4 text-lg text-white/90">
                    <Badge variant="secondary" className="bg-white/20 text-white border-white/30">
                      Management
                    </Badge>
                    <span>Professional Development</span>
                  </div>
                  <p className="mt-3 text-white/80 max-w-2xl">
                    Manage your coaching staff, track certifications, and optimize team performance through expert leadership
                  </p>
                </div>
              </div>

              {/* Quick Stats */}
              <div className="hidden lg:flex flex-col gap-3">
                <div className="bg-white/10 backdrop-blur-sm rounded-lg p-4 text-center min-w-[100px]">
                  <div className="text-2xl font-bold">{(coaches as Coach[] || []).length}</div>
                  <div className="text-sm text-white/80">Total Coaches</div>
                </div>
                <div className="bg-white/10 backdrop-blur-sm rounded-lg p-4 text-center min-w-[100px]">
                  <div className="text-2xl font-bold">{(coaches as Coach[] || []).filter((c: Coach) => c.status === 'active').length}</div>
                  <div className="text-sm text-white/80">Active</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="p-6">
        {/* Action Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">Coach Management</h2>
              <p className="text-gray-600">Manage coaching staff and their assignments</p>
            </div>
            <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="h-4 w-4 mr-2" />
                  Add Coach
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-2xl">
                <DialogHeader>
                  <DialogTitle>Add New Coach</DialogTitle>
                  <DialogDescription>
                    Add a new coach to your sports organization
                  </DialogDescription>
                </DialogHeader>
                <CoachForm onSuccess={() => setShowCreateDialog(false)} />
              </DialogContent>
            </Dialog>
          </div>

          {/* Filters */}
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
              <Input
                placeholder="Search coaches..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-full sm:w-40">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="inactive">Inactive</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Coaches Grid */}
        {filteredCoaches.length === 0 ? (
          <Card className="text-center py-12">
            <CardContent>
              <UserCheck className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-gray-900 mb-2">No coaches found</h3>
              <p className="text-gray-500 mb-4">
                {searchQuery || statusFilter !== "all" 
                  ? "No coaches match your search criteria" 
                  : "Get started by adding your first coach"}
              </p>
              {!searchQuery && statusFilter === "all" && (
                <Button onClick={() => setShowCreateDialog(true)}>
                  <Plus className="h-4 w-4 mr-2" />
                  Add Your First Coach
                </Button>
              )}
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredCoaches.map((coach: Coach) => (
              <Card key={coach.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <Avatar className="w-12 h-12">
                        <AvatarImage src={coach.profileImageUrl || undefined} alt={`${coach.firstName} ${coach.lastName}`} />
                        <AvatarFallback className="bg-warning text-white">
                          {coach.firstName[0]}{coach.lastName[0]}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <CardTitle className="text-lg">
                          {coach.firstName} {coach.lastName}
                        </CardTitle>
                        <CardDescription>{coach.specialization || "Coach"}</CardDescription>
                      </div>
                    </div>
                    <Badge variant={coach.status === "active" ? "default" : "secondary"}>
                      {coach.status}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2 text-sm text-gray-600">
                    {coach.email && (
                      <div className="flex items-center space-x-2">
                        <Mail className="h-4 w-4" />
                        <span>{coach.email}</span>
                      </div>
                    )}
                    {coach.phone && (
                      <div className="flex items-center space-x-2">
                        <Phone className="h-4 w-4" />
                        <span>{coach.phone}</span>
                      </div>
                    )}
                    {coach.experience && (
                      <div className="text-sm text-gray-500 mt-2">
                        {coach.experience} years experience
                      </div>
                    )}
                  </div>
                  <div className="flex items-center justify-between mt-4">
                    <p className="text-xs text-gray-500">
                      Joined {new Date(coach.createdAt!).toLocaleDateString()}
                    </p>
                    <div className="flex space-x-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleTeamAssignment(coach)}
                        title="Assign to teams"
                        data-testid={`assign-teams-${coach.id}`}
                      >
                        <Users className="h-4 w-4" />
                      </Button>
                      <Link to={`/coaches/${coach.id}`}>
                        <Button
                          variant="ghost"
                          size="sm"
                          title="View coach details"
                          data-testid={`view-coach-${coach.id}`}
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                      </Link>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(coach)}
                        title="Edit coach information"
                        data-testid={`edit-coach-${coach.id}`}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(coach.id)}
                        disabled={deleteCoachMutation.isPending}
                        title="Delete coach"
                        data-testid={`delete-coach-${coach.id}`}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Edit Dialog */}
        <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Edit Coach</DialogTitle>
              <DialogDescription>
                Update the coach information
              </DialogDescription>
            </DialogHeader>
            {selectedCoach && (
              <CoachForm
                coach={selectedCoach}
                onSuccess={() => {
                  setShowEditDialog(false);
                  setSelectedCoach(null);
                }}
              />
            )}
          </DialogContent>
        </Dialog>

        {/* Team Assignment Dialog */}
        <Dialog open={showTeamAssignDialog} onOpenChange={setShowTeamAssignDialog}>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Manage Team Assignments</DialogTitle>
              <DialogDescription>
                Assign {coachForTeamAssignment?.firstName} {coachForTeamAssignment?.lastName} to teams
              </DialogDescription>
            </DialogHeader>

            {/* Current Team Assignments */}
            <div className="space-y-4">
              <div>
                <h3 className="text-sm font-semibold mb-3">Current Team Assignments</h3>
                {coachTeams.length === 0 ? (
                  <p className="text-sm text-gray-500">No teams assigned yet</p>
                ) : (
                  <div className="space-y-2">
                    {coachTeams.map((assignment: any) => (
                      <div
                        key={assignment.id}
                        className="flex items-center justify-between p-3 border rounded-lg"
                        data-testid={`team-assignment-${assignment.teamId}`}
                      >
                        <div className="flex items-center space-x-3">
                          <Avatar className="h-8 w-8">
                            <AvatarImage src={assignment.teamLogoUrl || undefined} />
                            <AvatarFallback className="bg-blue-500 text-white text-xs">
                              {assignment.teamName.substring(0, 2).toUpperCase()}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <p className="font-medium text-sm">{assignment.teamName}</p>
                            <div className="flex items-center gap-2">
                              <Badge variant="secondary" className="text-xs">
                                {assignment.role.replace('_', ' ')}
                              </Badge>
                              <span className="text-xs text-gray-500">{assignment.teamSport}</span>
                            </div>
                          </div>
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveTeam(assignment.teamId)}
                          disabled={removeTeamMutation.isPending}
                          data-testid={`remove-team-${assignment.teamId}`}
                        >
                          <X className="h-4 w-4 text-red-500" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Assign New Team */}
              {availableTeams.length > 0 && (
                <div className="pt-4 border-t">
                  <h3 className="text-sm font-semibold mb-3">Assign to New Team</h3>
                  <div className="space-y-3">
                    <div>
                      <label className="text-sm font-medium mb-1 block">Select Team</label>
                      <Select value={selectedTeamId} onValueChange={setSelectedTeamId}>
                        <SelectTrigger data-testid="select-team">
                          <SelectValue placeholder="Choose a team" />
                        </SelectTrigger>
                        <SelectContent>
                          {availableTeams.map((team) => (
                            <SelectItem key={team.id} value={team.id.toString()}>
                              {team.name} ({team.sport})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <label className="text-sm font-medium mb-1 block">Role</label>
                      <Select value={selectedRole} onValueChange={setSelectedRole}>
                        <SelectTrigger data-testid="select-role">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="head_coach">Head Coach</SelectItem>
                          <SelectItem value="assistant_coach">Assistant Coach</SelectItem>
                          <SelectItem value="goalkeeper_coach">Goalkeeper Coach</SelectItem>
                          <SelectItem value="fitness_coach">Fitness Coach</SelectItem>
                          <SelectItem value="technical_coach">Technical Coach</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <Button
                      onClick={handleAssignTeam}
                      disabled={!selectedTeamId || assignTeamMutation.isPending}
                      className="w-full"
                      data-testid="assign-team-button"
                    >
                      <Plus className="h-4 w-4 mr-2" />
                      Assign to Team
                    </Button>
                  </div>
                </div>
              )}

              {availableTeams.length === 0 && coachTeams.length > 0 && (
                <div className="pt-4 border-t">
                  <p className="text-sm text-gray-500 text-center">
                    This coach is assigned to all available teams
                  </p>
                </div>
              )}
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}