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

const teamFormSchema = z.object({
  name: z.string().min(1, "Team name is required"),
  sport: z.string().min(1, "Sport is required"),
  status: z.enum(["active", "inactive"]),
  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().min(1800).max(new Date().getFullYear()).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().optional().or(z.literal("")),
  phone: z.string().optional(),
  position: z.string().optional(),
  jerseyNumber: z.number().min(1).max(99).optional(),
  status: z.enum(["active", "inactive", "injured", "suspended"]),
  height: z.number().min(100).max(250).optional(),
  weight: z.number().min(30).max(200).optional(),
});

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

export default function TeamDetailFixed() {
  const { id } = useParams();
  const teamId = parseInt(id || "");
  const { toast } = useToast();
  const queryClient = useQueryClient();
  
  // All state hooks
  const [editingTeam, setEditingTeam] = useState(false);
  const [editingPlayer, setEditingPlayer] = useState<number | null>(null);
  const [playerSearchTerm, setPlayerSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [genderFilter, setGenderFilter] = useState<string>("all");
  const [positionFilter, setPositionFilter] = useState<string>("all");
  const [showAddPlayer, setShowAddPlayer] = useState(false);
  const [showAddCoach, setShowAddCoach] = useState(false);

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

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

  // All query hooks
  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 { data: allTeams } = useQuery({
    queryKey: ["/api/teams"],
    enabled: !!teamId,
  });

  // All mutation hooks
  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) => {
      await apiRequest("PUT", `/api/teams/${teamId}`, teamData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
      setEditingTeam(false);
      toast({
        title: "Success",
        description: "Team updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update team",
        variant: "destructive",
      });
    },
  });

  const updatePlayerMutation = useMutation({
    mutationFn: async (data: PlayerEditData & { profileImage?: File }) => {
      const formData = new FormData();
      
      // Add all player data to FormData
      Object.entries(data).forEach(([key, value]) => {
        if (key === 'profileImage' && value instanceof File) {
          formData.append('profileImage', value);
        } else if (value !== undefined && value !== null) {
          formData.append(key, String(value));
        }
      });

      const response = await fetch(`/api/players/${editingPlayer}`, {
        method: "PUT",
        body: formData,
      });

      if (!response.ok) {
        throw new Error(await response.text());
      }

      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/player-stats`] });
      setEditingPlayer(null);
      toast({
        title: "Success",
        description: "Player updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update player",
        variant: "destructive",
      });
    },
  });

  const addCoachMutation = useMutation({
    mutationFn: async (coachId: number) => {
      await apiRequest("POST", `/api/teams/${teamId}/coaches`, { coachId, role: "assistant_coach" });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/teams/${teamId}/details`] });
      setShowAddCoach(false);
      toast({
        title: "Success",
        description: "Coach added to team successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to add coach",
        variant: "destructive",
      });
    },
  });

  // Query for available coaches
  const { data: availableCoaches } = useQuery({
    queryKey: ["/api/coaches"],
    enabled: showAddCoach,
  });

  // All effect hooks
  useEffect(() => {
    if (teamDetails) {
      const team = teamDetails as any;
      teamForm.reset({
        name: team?.name ?? "",
        sport: team?.sport ?? "rugby",
        status: team?.status ?? "active",
        description: team?.description ?? "",
        league: team?.league ?? "",
        homeVenue: team?.homeVenue ?? "",
        email: team?.email ?? "",
        phone: team?.phone ?? "",
        address: team?.address ?? "",
        foundedYear: team?.foundedYear ?? undefined,
      });
    }
  }, [teamDetails, teamForm]);

  useEffect(() => {
    if (editingPlayer && teamPlayers) {
      const player = teamPlayers.find((p: any) => p.id === editingPlayer);
      if (player) {
        playerEditForm.reset({
          firstName: player.firstName || "",
          lastName: player.lastName || "",
          email: player.email || "",
          phone: player.phone || "",
          position: player.position || "",
          jerseyNumber: player.jerseyNumber || undefined,
          status: player.status || "active",
          height: player.height || undefined,
          weight: player.weight || undefined,
        });
      }
    }
  }, [editingPlayer, teamPlayers, playerEditForm]);

  // Derived data
  const displayTeam = teamDetails || (Array.isArray(allTeams) ? allTeams.find((team: any) => team.id === teamId) : null);

  // Chart data preparation
  const genderChartData = playerStats && playerStats.byGender ? 
    Object.entries(playerStats.byGender).map(([gender, count]) => ({
      name: gender,
      value: count,
    })) : [];

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

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

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

  const handleEditTeam = () => {
    setEditingTeam(true);
  };

  // Early returns after all hooks
  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>
    );
  }

  if (!displayTeam) {
    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>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Link to="/teams">
            <Button variant="outline" size="sm">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back
            </Button>
          </Link>
          <div className="flex items-center space-x-3">
            <Avatar className="h-12 w-12">
              <AvatarImage src={(displayTeam as any)?.logoUrl} alt={(displayTeam as any)?.name || 'Team'} />
              <AvatarFallback>{((displayTeam as any)?.name || 'TM').slice(0, 2).toUpperCase()}</AvatarFallback>
            </Avatar>
            <div>
              <h1 className="text-3xl font-bold">{(displayTeam as any)?.name || 'Team Details'}</h1>
              <p className="text-gray-600 dark:text-gray-400 capitalize">{(displayTeam as any)?.sport || 'Sport'}</p>
            </div>
          </div>
        </div>
        <Dialog open={editingTeam} onOpenChange={setEditingTeam}>
          <DialogTrigger asChild>
            <Button onClick={handleEditTeam}>
              <Edit className="mr-2 h-4 w-4" />
              Edit Team
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <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 placeholder="Team name" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={teamForm.control}
                    name="sport"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sport</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Select sport" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="rugby">Rugby</SelectItem>
                            <SelectItem value="football">Football</SelectItem>
                            <SelectItem value="basketball">Basketball</SelectItem>
                            <SelectItem value="cricket">Cricket</SelectItem>
                            <SelectItem value="baseball">Baseball</SelectItem>
                            <SelectItem value="hockey">Hockey</SelectItem>
                            <SelectItem value="netball">Netball</SelectItem>
                            <SelectItem value="soccer">Soccer</SelectItem>
                            <SelectItem value="badminton">Badminton</SelectItem>
                            <SelectItem value="volleyball">Volleyball</SelectItem>
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={teamForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description</FormLabel>
                      <FormControl>
                        <Textarea placeholder="Team description" {...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 placeholder="League name" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={teamForm.control}
                    name="homeVenue"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Home Venue</FormLabel>
                        <FormControl>
                          <Input placeholder="Home venue" {...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" placeholder="team@example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={teamForm.control}
                    name="phone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Phone</FormLabel>
                        <FormControl>
                          <Input placeholder="Phone number" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={teamForm.control}
                  name="address"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Address</FormLabel>
                      <FormControl>
                        <Input placeholder="Team address" {...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" 
                            placeholder="Year founded" 
                            {...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">
                  <Button type="button" variant="outline" onClick={() => setEditingTeam(false)}>
                    Cancel
                  </Button>
                  <Button type="submit" disabled={updateTeamMutation.isPending}>
                    {updateTeamMutation.isPending ? "Updating..." : "Update Team"}
                  </Button>
                </div>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </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">
              {(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>
            <UserPlus className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {((displayTeam as any)?.coaches?.length || 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">
              {(displayTeam as any)?.foundedYear || 'N/A'}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Team Information */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>Team Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-sm font-medium text-gray-500">Status</p>
                <Badge variant={
                  (displayTeam as any)?.status === 'active' ? 'default' : 
                  (displayTeam as any)?.status === 'inactive' ? 'destructive' : 'secondary'
                }>
                  {((displayTeam as any)?.status || 'Unknown').charAt(0).toUpperCase() + ((displayTeam as any)?.status || 'unknown').slice(1)}
                </Badge>
              </div>
              <div>
                <p className="text-sm font-medium text-gray-500">Sport</p>
                <p className="font-medium capitalize">{(displayTeam as any)?.sport || 'N/A'}</p>
              </div>
            </div>
            
            {(displayTeam as any)?.description && (
              <div>
                <p className="text-sm font-medium text-gray-500">Description</p>
                <p className="text-sm">{(displayTeam as any).description}</p>
              </div>
            )}
            
            {(displayTeam as any)?.league && (
              <div>
                <p className="text-sm font-medium text-gray-500">League</p>
                <p className="text-sm">{(displayTeam as any).league}</p>
              </div>
            )}
            
            {(displayTeam as any)?.homeVenue && (
              <div>
                <p className="text-sm font-medium text-gray-500">Home Venue</p>
                <p className="text-sm">{(displayTeam as any).homeVenue}</p>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Contact Information</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {(displayTeam as any)?.email && (
              <div className="flex items-center space-x-2">
                <Mail className="h-4 w-4 text-gray-500" />
                <span className="text-sm">{(displayTeam as any).email}</span>
              </div>
            )}
            
            {(displayTeam as any)?.phone && (
              <div className="flex items-center space-x-2">
                <Phone className="h-4 w-4 text-gray-500" />
                <span className="text-sm">{(displayTeam as any).phone}</span>
              </div>
            )}
            
            {(displayTeam as any)?.address && (
              <div className="flex items-center space-x-2">
                <MapPin className="h-4 w-4 text-gray-500" />
                <span className="text-sm">{(displayTeam as any).address}</span>
              </div>
            )}
            
            {!(displayTeam as any)?.email && !(displayTeam as any)?.phone && !(displayTeam as any)?.address && (
              <p className="text-sm text-gray-500">No contact information available</p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Player Statistics */}
      {genderChartData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Player Demographics</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <h3 className="text-lg font-semibold mb-2">By Gender</h3>
                <ResponsiveContainer width="100%" height={200}>
                  <PieChart>
                    <Pie
                      data={genderChartData}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      outerRadius={80}
                      fill="#8884d8"
                      dataKey="value"
                      label={({ name, value }) => `${name}: ${value}`}
                    >
                      {genderChartData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={index % 2 === 0 ? '#0088FE' : '#FF8042'} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </div>
              
              <div>
                <h3 className="text-lg font-semibold mb-2">By Status</h3>
                <ResponsiveContainer width="100%" height={200}>
                  <BarChart data={statusChartData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="value" fill="#8884d8" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Players List */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Team Players ({(teamPlayers as any[])?.length || 0})</CardTitle>
            <Button onClick={() => setShowAddPlayer(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Add Player
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {(teamPlayers as any[])?.length > 0 ? (
            <div className="space-y-4">
              {(teamPlayers as any[]).map((player: any) => (
                <div key={player.id} className="flex items-center justify-between p-4 border rounded-lg">
                  <div className="flex items-center space-x-4">
                    <Avatar>
                      <AvatarImage src={player.profileImageUrl} />
                      <AvatarFallback>
                        {player.firstName?.[0]}{player.lastName?.[0]}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <p className="font-medium">{player.firstName} {player.lastName}</p>
                      <p className="text-sm text-gray-500">
                        {player.position || 'No position'} 
                        {player.jerseyNumber && ` • #${player.jerseyNumber}`}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant={player.status === 'active' ? 'default' : 'secondary'}>
                      {player.status}
                    </Badge>
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => setEditingPlayer(player.id)}
                    >
                      Edit
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <Users className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">No players</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by adding a player to this team.</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Coaches Section */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>Coaching Staff</CardTitle>
            <Button onClick={() => setShowAddCoach(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Add Coach
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {(displayTeam as any)?.coaches && (displayTeam as any).coaches.length > 0 ? (
            <div className="space-y-4">
              {(displayTeam as any).coaches.map((coach: any) => (
                <div key={coach.id} className="flex items-center justify-between p-4 border rounded-lg">
                  <div>
                    <p className="font-medium">Coach #{coach.coachId}</p>
                    <p className="text-sm text-gray-500 capitalize">{coach.role.replace('_', ' ')}</p>
                  </div>
                  <Button 
                    size="sm" 
                    variant="outline"
                    onClick={() => removeCoachMutation.mutate(coach.coachId)}
                  >
                    Remove
                  </Button>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <UserPlus className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-sm font-medium text-gray-900">No coaches</h3>
              <p className="mt-1 text-sm text-gray-500">Get started by adding a coach to this team.</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Player Edit Dialog */}
      <Dialog open={!!editingPlayer} onOpenChange={(open) => !open && setEditingPlayer(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Edit Player</DialogTitle>
          </DialogHeader>
          <Form {...playerEditForm}>
            <form onSubmit={playerEditForm.handleSubmit(handleUpdatePlayer)} className="space-y-4">
              {/* Profile Photo Upload */}
              <FormField
                control={playerEditForm.control}
                name="profileImage"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Profile Photo</FormLabel>
                    <FormControl>
                      <Input
                        type="file"
                        accept="image/*"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          field.onChange(file);
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={playerEditForm.control}
                  name="firstName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>First Name</FormLabel>
                      <FormControl>
                        <Input placeholder="First name" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={playerEditForm.control}
                  name="lastName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Last Name</FormLabel>
                      <FormControl>
                        <Input placeholder="Last name" {...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" placeholder="player@example.com" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={playerEditForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Phone</FormLabel>
                      <FormControl>
                        <Input placeholder="Phone number" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={playerEditForm.control}
                  name="dateOfBirth"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Date of Birth</FormLabel>
                      <FormControl>
                        <Input type="date" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={playerEditForm.control}
                  name="placeOfBirth"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Place of Birth</FormLabel>
                      <FormControl>
                        <Input placeholder="City, Country" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-3 gap-4">
                <FormField
                  control={playerEditForm.control}
                  name="position"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Position</FormLabel>
                      <FormControl>
                        <Input placeholder="Position" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={playerEditForm.control}
                  name="jerseyNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Jersey Number</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          placeholder="Jersey #" 
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={playerEditForm.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>
                          <SelectItem value="injured">Injured</SelectItem>
                          <SelectItem value="suspended">Suspended</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={playerEditForm.control}
                  name="height"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Height (cm)</FormLabel>
                      <FormControl>
                        <Input 
                          type="number" 
                          placeholder="Height in cm" 
                          {...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" 
                          placeholder="Weight in kg" 
                          {...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">
                <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 Coach Dialog */}
      <Dialog open={showAddCoach} onOpenChange={setShowAddCoach}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Add Coach to Team</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            {(availableCoaches as any[])?.length > 0 ? (
              <div className="space-y-2">
                <p className="text-sm text-gray-600">Select a coach to add to this team:</p>
                <div className="space-y-2 max-h-60 overflow-y-auto">
                  {(availableCoaches as any[]).map((coach: any) => (
                    <div key={coach.id} className="flex items-center justify-between p-3 border rounded-lg">
                      <div>
                        <p className="font-medium">{coach.firstName} {coach.lastName}</p>
                        <p className="text-sm text-gray-500">{coach.email}</p>
                      </div>
                      <Button 
                        size="sm"
                        onClick={() => addCoachMutation.mutate(coach.id)}
                        disabled={addCoachMutation.isPending}
                      >
                        {addCoachMutation.isPending ? "Adding..." : "Add"}
                      </Button>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="text-center py-8">
                <UserPlus className="mx-auto h-12 w-12 text-gray-400" />
                <h3 className="mt-2 text-sm font-medium text-gray-900">No available coaches</h3>
                <p className="mt-1 text-sm text-gray-500">All coaches are already assigned or none exist in the system.</p>
              </div>
            )}
            <div className="flex justify-end">
              <Button variant="outline" onClick={() => setShowAddCoach(false)}>
                Close
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}