import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useRoute } from "wouter";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { 
  Users, Mail, Phone, MapPin, Calendar, Trophy, 
  UserPlus, Edit, Trash2, ArrowLeft, BarChart3,
  Search, Filter, Grid3X3, List, Eye, Plus, Activity
} from "lucide-react";
import { Link } from "wouter";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { PieChart, Pie, Cell, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from "recharts";
import CoachForm from "@/components/forms/coach-form";
import PlayerForm from "@/components/forms/player-form";

const COLORS = ['#3B82F6', '#EF4444', '#10B981', '#F59E0B', '#8B5CF6'];



const teamFormSchema = z.object({
  name: z.string().min(1, "Team name is required"),
  sport: z.string().min(1, "Sport is required"),
  description: z.string().optional(),
  league: z.string().optional(),
  homeVenue: z.string().optional(),
  email: z.string().email().optional().or(z.literal("")),
  phone: z.string().optional(),
  address: z.string().optional(),
  foundedYear: z.number().optional(),
  status: z.enum(["active", "inactive"]).optional(),
});

const playerEditSchema = z.object({
  firstName: z.string().min(1, "First name is required"),
  lastName: z.string().min(1, "Last name is required"),
  email: z.string().email("Invalid email"),
  phone: z.string().optional(),
  position: z.string().optional(),
  jerseyNumber: z.number().optional(),
  status: z.enum(["active", "inactive", "injured", "suspended"]),
  height: z.number().optional(),
  weight: z.number().optional(),
});

type TeamFormData = z.infer<typeof teamFormSchema>;
type PlayerEditData = z.infer<typeof playerEditSchema>;

export default function TeamDetail() {
  const [, params] = useRoute("/teams/:id");
  const teamId = parseInt(params?.id || "0");
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [showAddPlayer, setShowAddPlayer] = useState(false);
  const [showAddCoach, setShowAddCoach] = useState(false);
  const [editingCoach, setEditingCoach] = useState<any>(null);
  const [showEditTeam, setShowEditTeam] = useState(false);
  
  // Player management states
  const [playerViewMode, setPlayerViewMode] = useState<'grid' | 'list'>('grid');
  const [playerSearchTerm, setPlayerSearchTerm] = useState("");
  const [playerStatusFilter, setPlayerStatusFilter] = useState<string>("all");
  const [playerGenderFilter, setPlayerGenderFilter] = useState<string>("all");
  const [editingPlayer, setEditingPlayer] = useState<any>(null);
  const [viewingPlayer, setViewingPlayer] = useState<any>(null);
  const [showViewPlayer, setShowViewPlayer] = useState(false);
  const [showPlayerDetails, setShowPlayerDetails] = useState<any>(null);

  // Player edit form
  const playerEditForm = useForm<PlayerEditData>({
    resolver: zodResolver(playerEditSchema),
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      position: "",
      jerseyNumber: undefined,
      status: "active",
      height: undefined,
      weight: undefined,
    },
  });

  const { data: teamDetails, isLoading: loadingDetails, error: teamError } = useQuery({
    queryKey: [`/api/teams/${teamId}/details`],
    enabled: !!teamId && !isNaN(teamId),
    retry: 3,
    retryDelay: 1000,
  });

  const { data: playerStats, isLoading: loadingStats, error: statsError } = useQuery({
    queryKey: [`/api/teams/${teamId}/player-stats`],
    enabled: !!teamId && !isNaN(teamId),
    retry: 3,
    retryDelay: 1000,
  });

  const { data: teamPlayers, isLoading: loadingPlayers } = useQuery({
    queryKey: [`/api/teams/${teamId}/player-stats`],
    enabled: !!teamId && !isNaN(teamId),
    select: (data: any) => data?.players || [],
    retry: 3,
    retryDelay: 1000,
  });


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



  const updateTeamMutation = useMutation({
    mutationFn: async (teamData: TeamFormData) => {
      return await apiRequest("PUT", `/api/teams/${teamId}`, teamData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
      queryClient.invalidateQueries({ queryKey: ["/api/teams"] });
      setShowEditTeam(false);
      toast({
        title: "Success",
        description: "Team updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update team",
        variant: "destructive",
      });
    },
  });



  const teamForm = useForm<TeamFormData>({
    resolver: zodResolver(teamFormSchema),
    defaultValues: {
      name: "",
      sport: "",
      description: "",
      league: "",
      homeVenue: "",
      email: "",
      phone: "",
      address: "",
      foundedYear: undefined,
      status: "active",
    },
  });

  // Update player mutation
  const updatePlayerMutation = useMutation({
    mutationFn: async (data: PlayerEditData) => {
      const formData = new FormData();
      Object.entries(data).forEach(([key, value]) => {
        if (value !== null && value !== undefined && value !== '') {
          formData.append(key, value.toString());
        }
      });
      // Preserve the current team ID to prevent player from being removed from team
      if (editingPlayer.teamId) {
        formData.append('teamId', editingPlayer.teamId.toString());
      }
      return await apiRequest("PUT", `/api/players/${editingPlayer.id}`, formData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/player-stats`] });
      setEditingPlayer(null);
      playerEditForm.reset();
      toast({
        title: "Success",
        description: "Player updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update player",
        variant: "destructive",
      });
    },
  });

  // Delete player mutation
  const deletePlayerMutation = useMutation({
    mutationFn: async (playerId: number) => {
      return await apiRequest("DELETE", `/api/players/${playerId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/player-stats`] });
      toast({
        title: "Success",
        description: "Player deleted successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to delete player",
        variant: "destructive",
      });
    },
  });

  const handleEditCoach = (coach: any) => {
    setEditingCoach(coach);
  };

  const handleDeletePlayer = (player: any) => {
    if (confirm(`Are you sure you want to delete ${player.firstName} ${player.lastName}?`)) {
      deletePlayerMutation.mutate(player.id);
    }
  };

  const handleEditTeam = () => {
    if (teamDetails) {
      teamForm.reset({
        name: (teamDetails as any).name || "",
        sport: (teamDetails as any).sport || "",
        description: (teamDetails as any).description || "",
        league: (teamDetails as any).league || "",
        homeVenue: (teamDetails as any).homeVenue || "",
        email: (teamDetails as any).email || "",
        phone: (teamDetails as any).phone || "",
        address: (teamDetails as any).address || "",
        foundedYear: (teamDetails as any).foundedYear || undefined,
        status: (teamDetails as any).status || "active",
      });
      setShowEditTeam(true);
    }
  };

  const handleUpdateTeam = (data: TeamFormData) => {
    updateTeamMutation.mutate(data);
  };

  const handleUpdatePlayer = (data: PlayerEditData) => {
    updatePlayerMutation.mutate(data);
  };

  // Populate player edit form when editing player changes
  useEffect(() => {
    if (editingPlayer) {
      playerEditForm.reset({
        firstName: editingPlayer.firstName || "",
        lastName: editingPlayer.lastName || "",
        email: editingPlayer.email || "",
        phone: editingPlayer.phone || "",
        position: editingPlayer.position || "",
        jerseyNumber: editingPlayer.jerseyNumber || undefined,
        status: editingPlayer.status || "active",
        height: editingPlayer.height || undefined,
        weight: editingPlayer.weight || undefined,
      });
    }
  }, [editingPlayer, playerEditForm]);

  if (isNaN(teamId)) {
    return (
      <div className="p-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-600">Invalid Team ID</h1>
          <Link to="/teams">
            <Button className="mt-4">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Teams
            </Button>
          </Link>
        </div>
      </div>
    );
  }

  if (loadingDetails || loadingStats) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/4"></div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-48 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // Always call this hook to maintain consistent hook order
  const { data: allTeams } = useQuery({
    queryKey: ["/api/teams"],
    enabled: !!teamId,
  });

  // Use team data from detailed query or fallback to basic teams list
  const displayTeam = teamDetails || (Array.isArray(allTeams) ? allTeams.find((team: any) => team.id === teamId) : null);

  // Show team data if available, even if not all details are loaded
  if (!displayTeam && !loadingDetails && !Array.isArray(allTeams)) {
    return (
      <div className="p-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-600">Team Not Found</h1>
          <p className="text-gray-600 mt-2">The team with ID {teamId} could not be found.</p>
          <Link to="/teams">
            <Button className="mt-4">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Teams
            </Button>
          </Link>
        </div>
      </div>
    );
  }

  // Prepare chart data with safe property access
  const genderChartData = playerStats && (playerStats as any).byGender ? 
    Object.entries((playerStats as any).byGender).map(([gender, count]) => ({
      name: gender,
      value: count,
    })) : [];

  const statusChartData = playerStats && (playerStats as any).byStatus ? 
    Object.entries((playerStats as any).byStatus).map(([status, count]) => ({
      name: status,
      value: count,
    })) : [];

  // Filter players based on search and filters
  const filteredPlayers = teamPlayers?.filter((player: any) => {
    const matchesSearch = !playerSearchTerm || 
      `${player.firstName} ${player.lastName}`.toLowerCase().includes(playerSearchTerm.toLowerCase()) ||
      player.email?.toLowerCase().includes(playerSearchTerm.toLowerCase());
    
    const matchesStatus = playerStatusFilter === "all" || player.status === playerStatusFilter;
    const matchesGender = playerGenderFilter === "all" || player.gender === playerGenderFilter;
    
    return matchesSearch && matchesStatus && matchesGender;
  }) || [];

  return (
    <div className="space-y-6">
      {/* Beautiful Team Header with Gradient Background */}
      <div className="relative overflow-hidden bg-gradient-to-br from-blue-600 via-purple-600 to-blue-800 text-white">
        {/* Decorative background elements */}
        <div className="absolute inset-0">
          <div className="absolute top-0 left-0 w-72 h-72 bg-white/10 rounded-full blur-3xl -translate-x-1/2 -translate-y-1/2"></div>
          <div className="absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl translate-x-1/3 translate-y-1/3"></div>
        </div>

        <div className="relative px-6 py-8">
          <div className="flex items-start justify-between mb-6">
            <Link to="/teams">
              <Button variant="ghost" size="sm" className="text-white hover:bg-white/20">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Back to Teams
              </Button>
            </Link>
            <div className="flex gap-2">
              <Button 
                variant="ghost" 
                size="sm" 
                className="text-white hover:bg-white/20"
                onClick={() => setShowEditTeam(true)}
              >
                <Edit className="mr-2 h-4 w-4" />
                Edit Team
              </Button>
            </div>
          </div>

          <div className="flex items-center space-x-6">
            {/* Team Logo */}
            {displayTeam?.logoUrl && (
              <div className="w-24 h-24 bg-white/20 backdrop-blur-sm rounded-full p-3 flex items-center justify-center">
                <img 
                  src={displayTeam.logoUrl} 
                  alt="Team Logo"
                  className="w-18 h-18 object-contain"
                />
              </div>
            )}

            <div className="flex-1">
              <h1 className="text-4xl font-bold mb-2">{displayTeam?.name || "Unknown Team"}</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">
                  {displayTeam?.sport || "Unknown Sport"}
                </Badge>
                <Badge variant="outline" className="border-white/30 text-white">
                  {displayTeam?.status || "active"}
                </Badge>
              </div>
              {displayTeam?.description && (
                <p className="mt-3 text-white/80 max-w-2xl">{displayTeam.description}</p>
              )}
            </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">{(playerStats as any)?.total || 0}</div>
                <div className="text-sm text-white/80">Players</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">{(teamDetails as any)?.coaches?.length || 0}</div>
                <div className="text-sm text-white/80">Coaches</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="p-6 space-y-6">
        {/* Team Management Actions */}
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold">Team Management</h2>
          <div className="flex gap-2">
            <Button onClick={() => setShowAddPlayer(true)}>
              <UserPlus className="mr-2 h-4 w-4" />
              Add Player
            </Button>
          </div>
        </div>
        
        {/* Team Overview */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Players</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{(playerStats as any)?.total || 0}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Active Players</CardTitle>
            <Trophy className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {(playerStats as any)?.byStatus?.active || 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Coaches</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{(teamDetails as any)?.coachCount || 0}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Founded</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {(teamDetails as any)?.foundedYear || 'N/A'}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Gender Distribution Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <BarChart3 className="mr-2 h-5 w-5" />
              Player Distribution by Gender
            </CardTitle>
          </CardHeader>
          <CardContent>
            {genderChartData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={genderChartData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, value, percent }) => `${name}: ${value} (${(percent * 100).toFixed(0)}%)`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {genderChartData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500">
                No player data available
              </div>
            )}
          </CardContent>
        </Card>

        {/* Status Distribution Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <BarChart3 className="mr-2 h-5 w-5" />
              Player Status Distribution
            </CardTitle>
          </CardHeader>
          <CardContent>
            {statusChartData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={statusChartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="value" fill="#3B82F6" />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex items-center justify-center h-64 text-gray-500">
                No status data available
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Team Information */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Contact Information */}
        <Card>
          <CardHeader>
            <CardTitle>Contact Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {(teamDetails as any)?.email && (
              <div className="flex items-center space-x-3">
                <Mail className="h-5 w-5 text-gray-500" />
                <div>
                  <p className="font-medium">Email</p>
                  <p className="text-gray-600 dark:text-gray-400">{(teamDetails as any).email}</p>
                </div>
              </div>
            )}
            
            {(teamDetails as any)?.phone && (
              <div className="flex items-center space-x-3">
                <Phone className="h-5 w-5 text-gray-500" />
                <div>
                  <p className="font-medium">Phone</p>
                  <p className="text-gray-600 dark:text-gray-400">{(teamDetails as any).phone}</p>
                </div>
              </div>
            )}
            
            {(teamDetails as any)?.address && (
              <div className="flex items-center space-x-3">
                <MapPin className="h-5 w-5 text-gray-500" />
                <div>
                  <p className="font-medium">Address</p>
                  <p className="text-gray-600 dark:text-gray-400">{(teamDetails as any).address}</p>
                </div>
              </div>
            )}

            {!(teamDetails as any)?.email && !(teamDetails as any)?.phone && !(teamDetails as any)?.address && (
              <p className="text-gray-500 italic">No contact information available</p>
            )}
          </CardContent>
        </Card>

        {/* Team Details */}
        <Card>
          <CardHeader>
            <CardTitle>Team Details</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <p className="font-medium">Description</p>
              <p className="text-gray-600 dark:text-gray-400">
                {(teamDetails as any)?.description || 'No description available'}
              </p>
            </div>
            
            <div>
              <p className="font-medium">League</p>
              <p className="text-gray-600 dark:text-gray-400">
                {(teamDetails as any)?.league || 'No league assigned'}
              </p>
            </div>
            
            <div>
              <p className="font-medium">Home Venue</p>
              <p className="text-gray-600 dark:text-gray-400">
                {(teamDetails as any)?.homeVenue || 'No home venue specified'}
              </p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Coaches Section */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Coaching Staff</CardTitle>
          <Button onClick={() => setShowAddCoach(true)}>
            <UserPlus className="mr-2 h-4 w-4" />
            Add Coach
          </Button>
        </CardHeader>
        <CardContent>
          {(teamDetails as any)?.coaches && (teamDetails as any).coaches.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {(teamDetails as any).coaches.map((teamCoach: any) => (
                <div key={teamCoach.id} className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="flex items-center space-x-3">
                    <Avatar>
                      <AvatarImage src={teamCoach.coach?.profileImageUrl} />
                      <AvatarFallback>
                        {teamCoach.coach?.firstName?.charAt(0)}{teamCoach.coach?.lastName?.charAt(0)}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <p className="font-medium">{teamCoach.coach?.firstName} {teamCoach.coach?.lastName}</p>
                      <p className="text-sm text-gray-600 dark:text-gray-400">{teamCoach.role || 'Coach'}</p>
                    </div>
                  </div>
                  <div className="flex space-x-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEditCoach(teamCoach.coach)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => removeCoachMutation.mutate(teamCoach.coachId)}
                      disabled={removeCoachMutation.isPending}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-gray-500 text-center py-8">No coaches assigned to this team</p>
          )}
        </CardContent>
      </Card>

      {/* Team Members List - Advanced Roster Management */}
      <Card className="bg-gray-50">
        <CardHeader className="bg-white border-b">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <div>
                <CardTitle className="text-xl text-gray-600">Team Members List</CardTitle>
              </div>
              <div className="flex items-center space-x-2 text-sm text-gray-500">
                <span>Switch Team:</span>
                <Select value={(teamDetails as any)?.name || ""}>
                  <SelectTrigger className="w-48 text-sm">
                    <SelectValue placeholder="Select team" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={(teamDetails as any)?.name || ""}>{(teamDetails as any)?.name} (Team Manager)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Button variant="outline" size="sm">
                <Users className="h-4 w-4 mr-2" />
                Bulk Actions
              </Button>
              <Button variant="outline" size="sm">
                Export
              </Button>
              <Button variant="outline" className="text-sm" onClick={() => setShowAddPlayer(true)}>
                + Add Member
              </Button>
            </div>
          </div>
          
          {/* Advanced Filters and Search */}
          <div className="mt-4 space-y-4">
            <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
              <div className="flex flex-col sm:flex-row gap-4 flex-1">
                {/* Enhanced Search */}
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    placeholder="Search by name, email, phone..."
                    value={playerSearchTerm}
                    onChange={(e) => setPlayerSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                
                {/* Advanced Filters */}
                <div className="flex gap-2">
                  <Select value={playerStatusFilter} onValueChange={setPlayerStatusFilter}>
                    <SelectTrigger className="w-32">
                      <SelectValue placeholder="Status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Status</SelectItem>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="inactive">Inactive</SelectItem>
                      <SelectItem value="injured">Injured</SelectItem>
                      <SelectItem value="suspended">Suspended</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <Select value={playerGenderFilter} onValueChange={setPlayerGenderFilter}>
                    <SelectTrigger className="w-32">
                      <SelectValue placeholder="Gender" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Genders</SelectItem>
                      <SelectItem value="male">Male</SelectItem>
                      <SelectItem value="female">Female</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <Select>
                    <SelectTrigger className="w-32">
                      <SelectValue placeholder="Position" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Positions</SelectItem>
                      <SelectItem value="forward">Forward</SelectItem>
                      <SelectItem value="back">Back</SelectItem>
                      <SelectItem value="center">Center</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <Select>
                    <SelectTrigger className="w-32">
                      <SelectValue placeholder="Age Group" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Ages</SelectItem>
                      <SelectItem value="u18">Under 18</SelectItem>
                      <SelectItem value="u21">Under 21</SelectItem>
                      <SelectItem value="senior">Senior</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              
              {/* View and Sort Options */}
              <div className="flex items-center gap-2">
                <Select>
                  <SelectTrigger className="w-32">
                    <SelectValue placeholder="Sort by" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="name">Name</SelectItem>
                    <SelectItem value="jersey">Jersey #</SelectItem>
                    <SelectItem value="position">Position</SelectItem>
                    <SelectItem value="age">Age</SelectItem>
                    <SelectItem value="joined">Date Joined</SelectItem>
                  </SelectContent>
                </Select>
                
                <div className="flex items-center gap-1 border rounded-lg p-1">
                  <Button
                    variant={playerViewMode === 'grid' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setPlayerViewMode('grid')}
                  >
                    <Grid3X3 className="h-4 w-4" />
                  </Button>
                  <Button
                    variant={playerViewMode === 'list' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => setPlayerViewMode('list')}
                  >
                    <List className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>
            
            {/* Quick Stats Bar */}
            <div className="flex items-center justify-between text-sm text-gray-600 bg-white rounded-lg p-3">
              <div className="flex items-center space-x-6">
                <span>Total: <strong>{filteredPlayers.length}</strong></span>
                <span>Active: <strong>{filteredPlayers.filter((p: any) => p.status === 'active').length}</strong></span>
                <span>Inactive: <strong>{filteredPlayers.filter((p: any) => p.status === 'inactive').length}</strong></span>
                <span>Male: <strong>{filteredPlayers.filter((p: any) => p.gender === 'male').length}</strong></span>
                <span>Female: <strong>{filteredPlayers.filter((p: any) => p.gender === 'female').length}</strong></span>
              </div>
              <Button variant="ghost" size="sm">
                <Filter className="h-4 w-4 mr-2" />
                Clear Filters
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6">
          <div className="mb-6">
            <h3 className="text-lg font-medium text-gray-700 mb-4">Players</h3>
          </div>
          
          {loadingPlayers ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="h-48 bg-gray-200 rounded animate-pulse"></div>
              ))}
            </div>
          ) : filteredPlayers.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredPlayers.map((player: any) => (
                <Card key={player.id} className="bg-white hover:shadow-lg transition-all duration-200 border-0 shadow-sm group">
                  <CardContent className="p-6">
                    {/* Selection Checkbox */}
                    <div className="flex items-start space-x-4 mb-4">
                      <div className="flex items-center space-x-3">
                        <input 
                          type="checkbox" 
                          className="rounded border-gray-300"
                          onChange={(e) => {
                            // Handle player selection for bulk actions
                          }}
                        />
                        <Avatar className="w-12 h-12 border-2 border-gray-100">
                          <AvatarImage src={player.profileImageUrl} alt={`${player.firstName} ${player.lastName}`} />
                          <AvatarFallback className="bg-blue-100 text-blue-600 font-semibold">
                            {player.firstName?.[0]}{player.lastName?.[0]}
                          </AvatarFallback>
                        </Avatar>
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <h4 className="font-semibold text-blue-600 text-lg hover:underline cursor-pointer">
                            {player.firstName} {player.lastName}
                          </h4>
                          <div className="opacity-0 group-hover:opacity-100 transition-opacity">
                            <Button 
                              variant="ghost" 
                              size="sm" 
                              className="h-6 w-6 p-0"
                              onClick={() => {
                                setViewingPlayer(player);
                                setShowViewPlayer(true);
                              }}
                            >
                              <Eye className="h-3 w-3" />
                            </Button>
                          </div>
                        </div>
                        <div className="space-y-1 text-sm text-gray-600 mt-2">
                          <div className="flex items-center">
                            <span className="font-medium w-16">Dad</span>
                            <span>{player.phone || "516-555-0005"}</span>
                          </div>
                          <div className="flex items-center">
                            <span className="font-medium w-16">Email</span>
                            <span className="text-blue-500">{player.email || "player@team.com"}</span>
                          </div>
                          <div className="flex items-center">
                            <span className="font-medium w-16">Position</span>
                            <span>{player.position || "Forward"}</span>
                          </div>
                          <div className="flex items-center">
                            <span className="font-medium w-16">Age</span>
                            <span>{player.dateOfBirth ? new Date().getFullYear() - new Date(player.dateOfBirth).getFullYear() : "22"}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <div className="relative">
                          <div className="w-12 h-16 bg-white border-2 border-gray-200 rounded flex items-center justify-center">
                            <span className="text-lg font-bold text-gray-700">
                              {player.jerseyNumber || "5"}
                            </span>
                          </div>
                          <div className="absolute -bottom-1 left-0 right-0 text-center">
                            <span className="text-xs font-medium text-gray-500 bg-white px-1">Player</span>
                          </div>
                        </div>
                        
                        {/* Player Performance Indicators */}
                        <div className="flex flex-col space-y-1">
                          <div className="flex items-center space-x-1">
                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                            <span className="text-xs text-gray-500">Available</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <Trophy className="h-3 w-3 text-yellow-500" />
                            <span className="text-xs text-gray-500">5 Goals</span>
                          </div>
                        </div>
                      </div>
                      
                      <div className="flex items-center space-x-2">
                        <Badge 
                          className={`px-3 py-1 text-xs font-medium ${
                            player.status === 'active' 
                              ? 'bg-green-100 text-green-700 border-green-200 hover:bg-green-200'
                              : 'bg-gray-100 text-gray-700 border-gray-200'
                          }`}
                        >
                          {player.status?.toUpperCase() || 'ACTIVE'}
                        </Badge>
                        
                        {/* Action Menu */}
                        <div className="flex items-center space-x-1">
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            className="p-1 h-auto"
                            onClick={() => {
                              setViewingPlayer(player);
                              setShowViewPlayer(true);
                            }}
                          >
                            <Eye className="h-4 w-4 text-gray-400 hover:text-gray-600" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => setEditingPlayer(player)} className="p-1 h-auto">
                            <Edit className="h-4 w-4 text-gray-400 hover:text-gray-600" />
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            className="p-1 h-auto"
                            onClick={() => handleDeletePlayer(player)}
                            disabled={deletePlayerMutation.isPending}
                          >
                            <Trash2 className="h-4 w-4 text-red-400 hover:text-red-600" />
                          </Button>
                        </div>
                      </div>
                    </div>
                    
                    {/* Additional Player Info on Hover */}
                    <div className="mt-3 pt-3 border-t border-gray-100 opacity-0 group-hover:opacity-100 transition-opacity">
                      <div className="flex items-center justify-between text-xs text-gray-500">
                        <span>Last Activity: 2 days ago</span>
                        <span>Attendance: 95%</span>
                        <span>Joined: {new Date().toLocaleDateString()}</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          ) : (
            <div className="text-center py-16 bg-white rounded-lg border-2 border-dashed border-gray-200">
              <Users className="h-16 w-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-xl font-semibold text-gray-700 mb-2">No team members yet</h3>
              <p className="text-gray-500 mb-6 max-w-md mx-auto">
                Start building your team roster by adding your first player. You can manage their positions, 
                jersey numbers, and contact information.
              </p>
              <div className="flex items-center justify-center space-x-3">
                <Button onClick={() => setShowAddPlayer(true)} className="bg-blue-600 hover:bg-blue-700">
                  <Plus className="h-4 w-4 mr-2" />
                  Add First Player
                </Button>
                <Button variant="outline">
                  <Users className="h-4 w-4 mr-2" />
                  Import Players
                </Button>
              </div>
            </div>
          )}
          
          {/* Bulk Actions Footer (shows when players are selected) */}
          <div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200 hidden">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <span className="text-sm font-medium text-blue-700">
                  3 players selected
                </span>
                <div className="flex items-center space-x-2">
                  <Button size="sm" variant="outline">
                    <Mail className="h-4 w-4 mr-2" />
                    Send Email
                  </Button>
                  <Button size="sm" variant="outline">
                    <Users className="h-4 w-4 mr-2" />
                    Change Status
                  </Button>
                  <Button size="sm" variant="outline">
                    <Trash2 className="h-4 w-4 mr-2" />
                    Remove from Team
                  </Button>
                </div>
              </div>
              <Button size="sm" variant="ghost">
                Clear Selection
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Add/Edit Coach Dialog */}
      <Dialog open={showAddCoach || !!editingCoach} onOpenChange={(open) => {
        if (!open) {
          setShowAddCoach(false);
          setEditingCoach(null);
        }
      }}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingCoach ? "Edit Coach" : "Add New Coach"}</DialogTitle>
          </DialogHeader>
          <CoachForm
            coach={editingCoach}
            onSuccess={() => {
              queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
              setShowAddCoach(false);
              setEditingCoach(null);
            }}
          />
        </DialogContent>
      </Dialog>

      {/* Edit Team Dialog */}
      <Dialog open={showEditTeam} onOpenChange={setShowEditTeam}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Team</DialogTitle>
          </DialogHeader>
          <Form {...teamForm}>
            <form onSubmit={teamForm.handleSubmit(handleUpdateTeam)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={teamForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Team Name</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={teamForm.control}
                  name="sport"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Sport</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              
              <FormField
                control={teamForm.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <Textarea {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={teamForm.control}
                  name="league"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>League</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={teamForm.control}
                  name="homeVenue"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Home Venue</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={teamForm.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Email</FormLabel>
                      <FormControl>
                        <Input type="email" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={teamForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Phone</FormLabel>
                      <FormControl>
                        <Input 
                          type="tel" 
                          {...field}
                          onChange={(e) => {
                            // Allow only numbers, spaces, dashes, parentheses, and plus sign
                            const value = e.target.value.replace(/[^+\d\s\-\(\)]/g, '');
                            field.onChange(value);
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              
              <FormField
                control={teamForm.control}
                name="address"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Address</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={teamForm.control}
                  name="foundedYear"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Founded Year</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          {...field} 
                          onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={teamForm.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Status</FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="Select status" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="active">Active</SelectItem>
                          <SelectItem value="inactive">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              
              <div className="flex justify-end space-x-2 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setShowEditTeam(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  disabled={updateTeamMutation.isPending}
                >
                  {updateTeamMutation.isPending ? "Updating..." : "Update Team"}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Player Details Dialog */}
      <Dialog open={!!showPlayerDetails} onOpenChange={(open) => {
        if (!open) setShowPlayerDetails(null);
      }}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Player Details</DialogTitle>
          </DialogHeader>
          {showPlayerDetails && (
            <div className="space-y-4">
              <div className="flex items-center space-x-4">
                <Avatar className="h-16 w-16">
                  <AvatarImage src={showPlayerDetails.profileImageUrl} />
                  <AvatarFallback>
                    {showPlayerDetails.firstName?.charAt(0)}{showPlayerDetails.lastName?.charAt(0)}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <h3 className="text-xl font-semibold">
                    {showPlayerDetails.firstName} {showPlayerDetails.lastName}
                  </h3>
                  <p className="text-gray-600">{showPlayerDetails.position || 'Player'}</p>
                  <Badge variant={showPlayerDetails.status === 'active' ? 'default' : 'secondary'}>
                    {showPlayerDetails.status}
                  </Badge>
                </div>
              </div>
              
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="font-medium mb-2">Contact Information</h4>
                  <div className="space-y-2 text-sm">
                    {showPlayerDetails.email && (
                      <p><span className="font-medium">Email:</span> {showPlayerDetails.email}</p>
                    )}
                    {showPlayerDetails.phone && (
                      <p><span className="font-medium">Phone:</span> {showPlayerDetails.phone}</p>
                    )}
                    {showPlayerDetails.address && (
                      <p><span className="font-medium">Address:</span> {showPlayerDetails.address}</p>
                    )}
                  </div>
                </div>
                
                <div>
                  <h4 className="font-medium mb-2">Personal Information</h4>
                  <div className="space-y-2 text-sm">
                    {showPlayerDetails.dateOfBirth && (
                      <p><span className="font-medium">Age:</span> {new Date().getFullYear() - new Date(showPlayerDetails.dateOfBirth).getFullYear()}</p>
                    )}
                    {showPlayerDetails.gender && (
                      <p><span className="font-medium">Gender:</span> {showPlayerDetails.gender}</p>
                    )}
                    {showPlayerDetails.nationality && (
                      <p><span className="font-medium">Nationality:</span> {showPlayerDetails.nationality}</p>
                    )}
                  </div>
                </div>
              </div>
              
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="font-medium mb-2">Physical Information</h4>
                  <div className="space-y-2 text-sm">
                    {showPlayerDetails.height && (
                      <p><span className="font-medium">Height:</span> {showPlayerDetails.height} cm</p>
                    )}
                    {showPlayerDetails.weight && (
                      <p><span className="font-medium">Weight:</span> {showPlayerDetails.weight} kg</p>
                    )}
                    {showPlayerDetails.preferredFoot && (
                      <p><span className="font-medium">Preferred Foot:</span> {showPlayerDetails.preferredFoot}</p>
                    )}
                  </div>
                </div>
                
                <div>
                  <h4 className="font-medium mb-2">Team Information</h4>
                  <div className="space-y-2 text-sm">
                    {showPlayerDetails.jerseyNumber && (
                      <p><span className="font-medium">Jersey Number:</span> {showPlayerDetails.jerseyNumber}</p>
                    )}
                    {showPlayerDetails.joinedDate && (
                      <p><span className="font-medium">Joined:</span> {new Date(showPlayerDetails.joinedDate).toLocaleDateString()}</p>
                    )}
                    {showPlayerDetails.experienceLevel && (
                      <p><span className="font-medium">Experience:</span> {showPlayerDetails.experienceLevel}</p>
                    )}
                  </div>
                </div>
              </div>
              
              {(showPlayerDetails.emergencyContact || showPlayerDetails.medicalNotes || showPlayerDetails.dietaryRequirements) && (
                <div>
                  <h4 className="font-medium mb-2">Additional Information</h4>
                  <div className="space-y-2 text-sm">
                    {showPlayerDetails.emergencyContact && (
                      <p><span className="font-medium">Emergency Contact:</span> {showPlayerDetails.emergencyContact}</p>
                    )}
                    {showPlayerDetails.medicalNotes && (
                      <p><span className="font-medium">Medical Notes:</span> {showPlayerDetails.medicalNotes}</p>
                    )}
                    {showPlayerDetails.dietaryRequirements && (
                      <p><span className="font-medium">Dietary Requirements:</span> {showPlayerDetails.dietaryRequirements}</p>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Player Edit Dialog */}
      <Dialog open={!!editingPlayer} onOpenChange={(open) => {
        if (!open) {
          setEditingPlayer(null);
          playerEditForm.reset();
        }
      }}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Player</DialogTitle>
          </DialogHeader>
          {editingPlayer && (
            <Form {...playerEditForm}>
              <form onSubmit={playerEditForm.handleSubmit(handleUpdatePlayer)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={playerEditForm.control}
                    name="firstName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>First Name</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={playerEditForm.control}
                    name="lastName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Last Name</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={playerEditForm.control}
                    name="email"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Email</FormLabel>
                        <FormControl>
                          <Input type="email" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={playerEditForm.control}
                    name="phone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Phone</FormLabel>
                        <FormControl>
                          <Input 
                            type="tel"
                            {...field}
                            onChange={(e) => {
                              // Allow only numbers, spaces, dashes, parentheses, and plus sign
                              const value = e.target.value.replace(/[^+\d\s\-\(\)]/g, '');
                              field.onChange(value);
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={playerEditForm.control}
                    name="position"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Position</FormLabel>
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={playerEditForm.control}
                    name="jerseyNumber"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Jersey Number</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            {...field} 
                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                
                <div className="grid grid-cols-3 gap-4">
                  <FormField
                    control={playerEditForm.control}
                    name="status"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Status</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="active">Active</SelectItem>
                            <SelectItem value="inactive">Inactive</SelectItem>
                            <SelectItem value="injured">Injured</SelectItem>
                            <SelectItem value="suspended">Suspended</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={playerEditForm.control}
                    name="height"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Height (cm)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            {...field} 
                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={playerEditForm.control}
                    name="weight"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Weight (kg)</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            {...field} 
                            onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                
                <div className="flex justify-end space-x-2 pt-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setEditingPlayer(null)}
                  >
                    Cancel
                  </Button>
                  <Button 
                    type="submit"
                    disabled={updatePlayerMutation.isPending}
                  >
                    {updatePlayerMutation.isPending ? "Updating..." : "Update Player"}
                  </Button>
                </div>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* Add Player Dialog */}
      <Dialog open={showAddPlayer} onOpenChange={(open) => {
        if (!open) {
          setShowAddPlayer(false);
        }
      }}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Add New Player to {(teamDetails as any)?.name || 'Team'}</DialogTitle>
          </DialogHeader>
          <PlayerForm 
            teams={(allTeams as any) || []} 
            onSuccess={() => {
              setShowAddPlayer(false);
              queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
              queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/player-stats`] });
              queryClient.invalidateQueries({ queryKey: ["/api/players"] });
              toast({
                title: "Success",
                description: "Player added successfully",
              });
            }}
            preselectedTeamId={teamId}
          />
        </DialogContent>
      </Dialog>

      {/* View Player Dialog */}
      <Dialog open={showViewPlayer} onOpenChange={(open) => {
        if (!open) {
          setShowViewPlayer(false);
          setViewingPlayer(null);
        }
      }}>
        <DialogContent className="max-w-5xl w-[98vw] max-h-[95vh] overflow-y-auto p-0">
          <DialogHeader className="sr-only">
            <DialogTitle>{viewingPlayer?.firstName} {viewingPlayer?.lastName} - Player Details</DialogTitle>
          </DialogHeader>
          
          {viewingPlayer && (
            <div className="space-y-0">
              {/* Professional Gradient Header */}
              <div className="relative overflow-hidden bg-gradient-to-br from-primary via-blue-600 to-purple-600 p-8">
                {/* Decorative Background Elements */}
                <div className="absolute top-0 right-0 w-96 h-96 bg-white/10 rounded-full -translate-y-48 translate-x-48 blur-3xl"></div>
                <div className="absolute bottom-0 left-0 w-72 h-72 bg-white/5 rounded-full translate-y-36 -translate-x-36 blur-2xl"></div>
                
                {/* Content */}
                <div className="relative flex flex-col md:flex-row items-center md:items-start gap-6">
                  {/* Player Avatar */}
                  <div className="relative group">
                    <div className="absolute inset-0 bg-white/20 rounded-2xl blur-xl group-hover:blur-2xl transition-all"></div>
                    <Avatar className="relative w-32 h-32 md:w-40 md:h-40 border-4 border-white/30 shadow-2xl ring-4 ring-white/10">
                      <AvatarImage src={viewingPlayer.profileImageUrl} alt={`${viewingPlayer.firstName} ${viewingPlayer.lastName}`} />
                      <AvatarFallback className="bg-gradient-to-br from-white/20 to-white/10 text-white text-4xl font-bold">
                        {viewingPlayer.firstName?.[0]}{viewingPlayer.lastName?.[0]}
                      </AvatarFallback>
                    </Avatar>
                  </div>

                  {/* Player Info */}
                  <div className="flex-1 text-center md:text-left text-white">
                    <h1 className="text-3xl md:text-4xl font-bold mb-3 drop-shadow-lg">
                      {viewingPlayer.firstName} {viewingPlayer.lastName}
                    </h1>
                    
                    {/* Badges */}
                    <div className="flex flex-wrap items-center justify-center md:justify-start gap-3 mb-4">
                      <Badge className={`px-4 py-1.5 text-sm font-semibold shadow-lg ${
                        viewingPlayer.status === 'active' 
                          ? 'bg-green-500 text-white hover:bg-green-600' 
                          : 'bg-gray-500 text-white hover:bg-gray-600'
                      }`}>
                        {viewingPlayer.status?.toUpperCase() || 'ACTIVE'}
                      </Badge>
                      
                      {viewingPlayer.jerseyNumber && (
                        <div className="flex items-center px-4 py-1.5 bg-white/20 backdrop-blur-sm rounded-full border-2 border-white/30 shadow-lg">
                          <Trophy className="h-4 w-4 mr-2" />
                          <span className="font-bold">#{viewingPlayer.jerseyNumber}</span>
                        </div>
                      )}
                      
                      {viewingPlayer.position && (
                        <div className="px-4 py-1.5 bg-white/20 backdrop-blur-sm rounded-full border-2 border-white/30 shadow-lg">
                          <span className="font-semibold">{viewingPlayer.position}</span>
                        </div>
                      )}
                    </div>

                    {/* Quick Stats */}
                    <div className="grid grid-cols-3 gap-3 mt-6 max-w-md mx-auto md:mx-0">
                      <div className="bg-white/10 backdrop-blur-md rounded-xl p-4 text-center border border-white/20 hover:bg-white/20 transition-all">
                        <div className="text-2xl font-bold">{viewingPlayer.dateOfBirth ? new Date().getFullYear() - new Date(viewingPlayer.dateOfBirth).getFullYear() : 'N/A'}</div>
                        <div className="text-white/80 text-xs mt-1 uppercase tracking-wider">Age</div>
                      </div>
                      <div className="bg-white/10 backdrop-blur-md rounded-xl p-4 text-center border border-white/20 hover:bg-white/20 transition-all">
                        <div className="text-2xl font-bold">{viewingPlayer.height || 'N/A'}</div>
                        <div className="text-white/80 text-xs mt-1 uppercase tracking-wider">Height (cm)</div>
                      </div>
                      <div className="bg-white/10 backdrop-blur-md rounded-xl p-4 text-center border border-white/20 hover:bg-white/20 transition-all">
                        <div className="text-2xl font-bold">{viewingPlayer.weight || 'N/A'}</div>
                        <div className="text-white/80 text-xs mt-1 uppercase tracking-wider">Weight (kg)</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Information Cards */}
              <div className="p-6 space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                  {/* Contact Information Card */}
                  <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-blue-50 to-white dark:from-blue-950 dark:to-slate-900">
                    <CardHeader className="pb-3">
                      <CardTitle className="text-lg flex items-center gap-3">
                        <div className="p-2.5 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shadow-lg">
                          <Mail className="h-5 w-5 text-white" />
                        </div>
                        <span className="bg-gradient-to-r from-blue-600 to-blue-800 bg-clip-text text-transparent font-bold">
                          Contact Info
                        </span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      {viewingPlayer.email && (
                        <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-blue-100 dark:border-blue-900 hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                          <Mail className="h-4 w-4 text-blue-600 flex-shrink-0" />
                          <span className="text-sm text-gray-700 dark:text-gray-300 break-all font-medium">{viewingPlayer.email}</span>
                        </div>
                      )}
                      {viewingPlayer.phone && (
                        <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-blue-100 dark:border-blue-900 hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                          <Phone className="h-4 w-4 text-blue-600 flex-shrink-0" />
                          <span className="text-sm text-gray-700 dark:text-gray-300 font-medium">{viewingPlayer.phone}</span>
                        </div>
                      )}
                      {viewingPlayer.address && (
                        <div className="flex items-center gap-3 p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-blue-100 dark:border-blue-900 hover:border-blue-300 dark:hover:border-blue-700 transition-colors">
                          <MapPin className="h-4 w-4 text-blue-600 flex-shrink-0" />
                          <span className="text-sm text-gray-700 dark:text-gray-300 font-medium">{viewingPlayer.address}</span>
                        </div>
                      )}
                      {!viewingPlayer.email && !viewingPlayer.phone && !viewingPlayer.address && (
                        <p className="text-sm text-gray-500 italic p-3">No contact information available</p>
                      )}
                    </CardContent>
                  </Card>

                  {/* Physical Stats Card */}
                  <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-green-50 to-white dark:from-green-950 dark:to-slate-900">
                    <CardHeader className="pb-3">
                      <CardTitle className="text-lg flex items-center gap-3">
                        <div className="p-2.5 bg-gradient-to-br from-green-500 to-green-600 rounded-xl shadow-lg">
                          <BarChart3 className="h-5 w-5 text-white" />
                        </div>
                        <span className="bg-gradient-to-r from-green-600 to-green-800 bg-clip-text text-transparent font-bold">
                          Physical Stats
                        </span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-green-100 dark:border-green-900 hover:border-green-300 dark:hover:border-green-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">Height:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100">{viewingPlayer.height ? `${viewingPlayer.height} cm` : 'Not specified'}</span>
                      </div>
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-green-100 dark:border-green-900 hover:border-green-300 dark:hover:border-green-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">Weight:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100">{viewingPlayer.weight ? `${viewingPlayer.weight} kg` : 'Not specified'}</span>
                      </div>
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-green-100 dark:border-green-900 hover:border-green-300 dark:hover:border-green-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">BMI:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100">
                          {viewingPlayer.height && viewingPlayer.weight 
                            ? ((viewingPlayer.weight / ((viewingPlayer.height / 100) ** 2))).toFixed(1)
                            : 'N/A'
                          }
                        </span>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Personal Information Card */}
                  <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-purple-50 to-white dark:from-purple-950 dark:to-slate-900">
                    <CardHeader className="pb-3">
                      <CardTitle className="text-lg flex items-center gap-3">
                        <div className="p-2.5 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl shadow-lg">
                          <Calendar className="h-5 w-5 text-white" />
                        </div>
                        <span className="bg-gradient-to-r from-purple-600 to-purple-800 bg-clip-text text-transparent font-bold">
                          Personal Info
                        </span>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-purple-100 dark:border-purple-900 hover:border-purple-300 dark:hover:border-purple-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">Date of Birth:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100">{viewingPlayer.dateOfBirth ? new Date(viewingPlayer.dateOfBirth).toLocaleDateString() : 'Not specified'}</span>
                      </div>
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-purple-100 dark:border-purple-900 hover:border-purple-300 dark:hover:border-purple-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">Gender:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100 capitalize">{viewingPlayer.gender || 'Not specified'}</span>
                      </div>
                      <div className="flex justify-between items-center p-3 rounded-xl bg-white/80 dark:bg-slate-800/80 border border-purple-100 dark:border-purple-900 hover:border-purple-300 dark:hover:border-purple-700 transition-colors">
                        <span className="text-sm text-gray-600 dark:text-gray-400 font-semibold">Nationality:</span>
                        <span className="text-sm font-bold text-gray-900 dark:text-gray-100">{viewingPlayer.nationality || 'Not specified'}</span>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* Emergency Contact & Medical Information */}
                {(viewingPlayer.emergencyContact || viewingPlayer.medicalNotes) && (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mt-5">
                    {viewingPlayer.emergencyContact && (
                      <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-red-50 to-white dark:from-red-950 dark:to-slate-900">
                        <CardHeader className="pb-3">
                          <CardTitle className="text-lg flex items-center gap-3">
                            <div className="p-2.5 bg-gradient-to-br from-red-500 to-red-600 rounded-xl shadow-lg">
                              <Phone className="h-5 w-5 text-white" />
                            </div>
                            <span className="bg-gradient-to-r from-red-600 to-red-800 bg-clip-text text-transparent font-bold">
                              Emergency Contact
                            </span>
                          </CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="p-4 bg-white/80 dark:bg-slate-800/80 rounded-xl border border-red-100 dark:border-red-900">
                            <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed font-medium">{viewingPlayer.emergencyContact}</p>
                          </div>
                        </CardContent>
                      </Card>
                    )}
                    
                    {viewingPlayer.medicalNotes && (
                      <Card className="border-0 shadow-lg hover:shadow-xl transition-all duration-300 bg-gradient-to-br from-orange-50 to-white dark:from-orange-950 dark:to-slate-900">
                        <CardHeader className="pb-3">
                          <CardTitle className="text-lg flex items-center gap-3">
                            <div className="p-2.5 bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl shadow-lg">
                              <Activity className="h-5 w-5 text-white" />
                            </div>
                            <span className="bg-gradient-to-r from-orange-600 to-orange-800 bg-clip-text text-transparent font-bold">
                              Medical Notes
                            </span>
                          </CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="p-4 bg-white/80 dark:bg-slate-800/80 rounded-xl border border-orange-100 dark:border-orange-900">
                            <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed font-medium">{viewingPlayer.medicalNotes}</p>
                          </div>
                        </CardContent>
                      </Card>
                    )}
                  </div>
                )}

                {/* Action Buttons */}
                <div className="flex flex-col sm:flex-row gap-3 pt-4 border-t mt-6">
                  <Button 
                    onClick={() => {
                      setShowViewPlayer(false);
                      setViewingPlayer(null);
                      setEditingPlayer(viewingPlayer);
                    }}
                    className="flex-1 sm:flex-none bg-gradient-to-r from-primary to-blue-600 hover:from-primary/90 hover:to-blue-600/90 shadow-lg"
                    aria-label="Edit player details"
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    Edit Player
                  </Button>
                  <Button 
                    variant="outline"
                    onClick={() => {
                      setShowViewPlayer(false);
                      setViewingPlayer(null);
                    }}
                    className="flex-1 sm:flex-none"
                    aria-label="Close player details"
                  >
                    Close
                  </Button>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
      </div>
    </div>
  );
}