import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { Plus, Edit, Trash2, Search, Trophy, Users, Calendar, Medal, Eye, X } from "lucide-react";
import type { League, LeagueTeam, Team } from "@shared/schema";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";

const leagueFormSchema = z.object({
  name: z.string().min(1, "Name is required"),
  sport: z.string().min(1, "Sport is required"),
  season: z.string().min(1, "Season is required"),
  division: z.string().optional(),
  description: z.string().optional(),
  logoUrl: z.string().optional(),
  status: z.string().default("active"),
  startDate: z.string(),
  endDate: z.string(),
  maxTeams: z.number().optional(),
  registrationDeadline: z.string().optional(),
  rules: z.string().optional(),
  pointsForWin: z.number().default(3),
  pointsForDraw: z.number().default(1),
  pointsForLoss: z.number().default(0),
});

type LeagueFormValues = z.infer<typeof leagueFormSchema>;

export default function Leagues() {
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [sportFilter, setSportFilter] = useState<string>("all");
  const [selectedLeague, setSelectedLeague] = useState<League | null>(null);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showStandingsDialog, setShowStandingsDialog] = useState(false);
  const [showTeamsDialog, setShowTeamsDialog] = useState(false);
  const [leagueForStandings, setLeagueForStandings] = useState<League | null>(null);
  const [leagueForTeams, setLeagueForTeams] = useState<League | null>(null);
  const [selectedTeamId, setSelectedTeamId] = useState<string>("");
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: leagues, isLoading } = useQuery<League[]>({
    queryKey: ["/api/leagues"],
  });

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

  const { data: standings = [] } = useQuery<any[]>({
    queryKey: leagueForStandings ? [`/api/leagues/${leagueForStandings.id}/standings`] : [],
    enabled: !!leagueForStandings,
  });

  const form = useForm<LeagueFormValues>({
    resolver: zodResolver(leagueFormSchema),
    defaultValues: {
      name: "",
      sport: "",
      season: "",
      division: "",
      description: "",
      logoUrl: "",
      status: "active",
      startDate: "",
      endDate: "",
      maxTeams: undefined,
      registrationDeadline: "",
      rules: "",
      pointsForWin: 3,
      pointsForDraw: 1,
      pointsForLoss: 0,
    },
  });

  const createLeagueMutation = useMutation({
    mutationFn: async (data: LeagueFormValues) => {
      await apiRequest("POST", "/api/leagues", data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/leagues"] });
      setShowCreateDialog(false);
      form.reset();
      toast({
        title: "Success",
        description: "League created successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to create league",
        variant: "destructive",
      });
    },
  });

  const updateLeagueMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: Partial<LeagueFormValues> }) => {
      await apiRequest("PUT", `/api/leagues/${id}`, data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/leagues"] });
      setShowEditDialog(false);
      setSelectedLeague(null);
      toast({
        title: "Success",
        description: "League updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update league",
        variant: "destructive",
      });
    },
  });

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

  const addTeamToLeagueMutation = useMutation({
    mutationFn: async ({ leagueId, teamId }: { leagueId: number; teamId: number }) => {
      await apiRequest("POST", "/api/league-teams", { leagueId, teamId });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/leagues/${leagueForStandings?.id}/standings`] });
      setSelectedTeamId("");
      toast({
        title: "Success",
        description: "Team added to league successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to add team to league",
        variant: "destructive",
      });
    },
  });

  const removeTeamFromLeagueMutation = useMutation({
    mutationFn: async ({ leagueId, teamId }: { leagueId: number; teamId: number }) => {
      await apiRequest("DELETE", `/api/league-teams/${leagueId}/${teamId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/leagues/${leagueForStandings?.id}/standings`] });
      toast({
        title: "Success",
        description: "Team removed from league successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to remove team from league",
        variant: "destructive",
      });
    },
  });

  const filteredLeagues = (leagues || []).filter((league) => {
    const matchesSearch =
      league.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      league.sport.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (league.season || "").toLowerCase().includes(searchQuery.toLowerCase());

    const matchesStatus = statusFilter === "all" || league.status === statusFilter;
    const matchesSport = sportFilter === "all" || league.sport === sportFilter;

    return matchesSearch && matchesStatus && matchesSport;
  });

  const handleEdit = (league: League) => {
    setSelectedLeague(league);
    form.reset({
      name: league.name,
      sport: league.sport,
      season: league.season,
      division: league.division || "",
      description: league.description || "",
      logoUrl: league.logoUrl || "",
      status: league.status,
      startDate: league.startDate,
      endDate: league.endDate,
      maxTeams: league.maxTeams || undefined,
      registrationDeadline: league.registrationDeadline || "",
      rules: league.rules || "",
      pointsForWin: league.pointsForWin ?? 3,
      pointsForDraw: league.pointsForDraw ?? 1,
      pointsForLoss: league.pointsForLoss ?? 0,
    });
    setShowEditDialog(true);
  };

  const handleDelete = async (leagueId: number) => {
    if (window.confirm("Are you sure you want to delete this league? This will also remove all team associations.")) {
      deleteLeagueMutation.mutate(leagueId);
    }
  };

  const handleViewStandings = (league: League) => {
    setLeagueForStandings(league);
    setShowStandingsDialog(true);
  };

  const handleAddTeam = () => {
    if (!selectedTeamId || !leagueForStandings) return;

    addTeamToLeagueMutation.mutate({
      leagueId: leagueForStandings.id,
      teamId: parseInt(selectedTeamId),
    });
  };

  const handleRemoveTeam = (teamId: number) => {
    if (!leagueForStandings) return;

    if (window.confirm("Are you sure you want to remove this team from the league?")) {
      removeTeamFromLeagueMutation.mutate({
        leagueId: leagueForStandings.id,
        teamId,
      });
    }
  };

  const onSubmit = (data: LeagueFormValues) => {
    if (selectedLeague) {
      updateLeagueMutation.mutate({ id: selectedLeague.id, data });
    } else {
      createLeagueMutation.mutate(data);
    }
  };

  const uniqueSports = Array.from(new Set((leagues || []).map((l) => l.sport)));

  // Get teams not already in the league
  const teamsInLeague = new Set(standings.map((s: any) => s.teamId));
  const availableTeams = teams.filter((team) => !teamsInLeague.has(team.id));

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

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-3xl font-bold flex items-center gap-2">
            <Trophy className="h-8 w-8 text-primary" />
            Leagues & Tournaments
          </h1>
          <p className="text-gray-600 mt-2">Manage leagues, tournaments, and standings</p>
        </div>
        <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
          <DialogTrigger asChild>
            <Button data-testid="button-create-league">
              <Plus className="h-4 w-4 mr-2" />
              Create League
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Create New League</DialogTitle>
              <DialogDescription>Add a new league or tournament to your organization</DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>League Name</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="Premier League" data-testid="input-league-name" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="sport"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sport</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="Football, Basketball, etc." data-testid="input-sport" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="season"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Season</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="2024/2025" data-testid="input-season" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="division"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Division (Optional)</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="Division 1" data-testid="input-division" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="startDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Start Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} data-testid="input-start-date" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="endDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>End Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} data-testid="input-end-date" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Description (Optional)</FormLabel>
                      <FormControl>
                        <Textarea {...field} placeholder="League description..." data-testid="input-description" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="grid grid-cols-3 gap-4">
                  <FormField
                    control={form.control}
                    name="pointsForWin"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Points for Win</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                            data-testid="input-points-win"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="pointsForDraw"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Points for Draw</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                            data-testid="input-points-draw"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="pointsForLoss"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Points for Loss</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                            data-testid="input-points-loss"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="flex justify-end gap-2">
                  <Button type="button" variant="outline" onClick={() => setShowCreateDialog(false)} data-testid="button-cancel">
                    Cancel
                  </Button>
                  <Button type="submit" disabled={createLeagueMutation.isPending} data-testid="button-submit">
                    {createLeagueMutation.isPending ? "Creating..." : "Create League"}
                  </Button>
                </div>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="flex flex-col md:flex-row gap-4 mb-6">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search leagues by name, sport, or season..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
            data-testid="input-search"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full md:w-48" data-testid="select-status">
            <SelectValue placeholder="All Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="upcoming">Upcoming</SelectItem>
          </SelectContent>
        </Select>
        <Select value={sportFilter} onValueChange={setSportFilter}>
          <SelectTrigger className="w-full md:w-48" data-testid="select-sport">
            <SelectValue placeholder="All Sports" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Sports</SelectItem>
            {uniqueSports.map((sport) => (
              <SelectItem key={sport} value={sport}>
                {sport}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {filteredLeagues.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16">
            <Trophy className="h-16 w-16 text-gray-400 mb-4" />
            <h3 className="text-xl font-semibold text-gray-700 mb-2">No leagues found</h3>
            <p className="text-gray-500 mb-4">
              {searchQuery || statusFilter !== "all" || sportFilter !== "all"
                ? "Try adjusting your filters"
                : "Get started by creating your first league"}
            </p>
            {!searchQuery && statusFilter === "all" && sportFilter === "all" && (
              <Button onClick={() => setShowCreateDialog(true)} data-testid="button-create-first">
                <Plus className="h-4 w-4 mr-2" />
                Create League
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredLeagues.map((league) => (
            <Card key={league.id} className="hover:shadow-lg transition-shadow" data-testid={`card-league-${league.id}`}>
              <CardHeader>
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <CardTitle className="text-xl">{league.name}</CardTitle>
                    <CardDescription className="mt-1">
                      {league.sport} • {league.season}
                    </CardDescription>
                  </div>
                  <Badge variant={league.status === "active" ? "default" : "secondary"}>
                    {league.status}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {league.division && (
                    <div className="flex items-center text-sm text-gray-600">
                      <Medal className="h-4 w-4 mr-2" />
                      {league.division}
                    </div>
                  )}
                  <div className="flex items-center text-sm text-gray-600">
                    <Calendar className="h-4 w-4 mr-2" />
                    {new Date(league.startDate).toLocaleDateString()} - {new Date(league.endDate).toLocaleDateString()}
                  </div>
                  {league.description && (
                    <p className="text-sm text-gray-600 line-clamp-2">{league.description}</p>
                  )}
                  <div className="flex items-center gap-2 text-xs text-gray-500">
                    <span>Win: {league.pointsForWin}pts</span>
                    <span>•</span>
                    <span>Draw: {league.pointsForDraw}pts</span>
                  </div>
                  <div className="flex gap-2 pt-4">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleViewStandings(league)}
                      data-testid={`button-standings-${league.id}`}
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      Standings
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleEdit(league)}
                      data-testid={`button-edit-${league.id}`}
                    >
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDelete(league.id)}
                      data-testid={`button-delete-${league.id}`}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Edit League Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit League</DialogTitle>
            <DialogDescription>Update league information</DialogDescription>
          </DialogHeader>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>League Name</FormLabel>
                      <FormControl>
                        <Input {...field} data-testid="input-edit-name" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="sport"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Sport</FormLabel>
                      <FormControl>
                        <Input {...field} data-testid="input-edit-sport" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="season"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Season</FormLabel>
                      <FormControl>
                        <Input {...field} data-testid="input-edit-season" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Status</FormLabel>
                      <Select value={field.value} onValueChange={field.onChange}>
                        <FormControl>
                          <SelectTrigger data-testid="select-edit-status">
                            <SelectValue />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="active">Active</SelectItem>
                          <SelectItem value="completed">Completed</SelectItem>
                          <SelectItem value="upcoming">Upcoming</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="flex justify-end gap-2">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    setShowEditDialog(false);
                    setSelectedLeague(null);
                  }}
                  data-testid="button-edit-cancel"
                >
                  Cancel
                </Button>
                <Button type="submit" disabled={updateLeagueMutation.isPending} data-testid="button-edit-submit">
                  {updateLeagueMutation.isPending ? "Updating..." : "Update League"}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Standings Dialog */}
      <Dialog open={showStandingsDialog} onOpenChange={setShowStandingsDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Trophy className="h-5 w-5" />
              {leagueForStandings?.name} - Standings
            </DialogTitle>
            <DialogDescription>League table and team management</DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="flex gap-2">
              <Select value={selectedTeamId} onValueChange={setSelectedTeamId}>
                <SelectTrigger className="flex-1" data-testid="select-add-team">
                  <SelectValue placeholder="Select team to add..." />
                </SelectTrigger>
                <SelectContent>
                  {availableTeams.map((team) => (
                    <SelectItem key={team.id} value={team.id.toString()}>
                      {team.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button
                onClick={handleAddTeam}
                disabled={!selectedTeamId || addTeamToLeagueMutation.isPending}
                data-testid="button-add-team"
              >
                <Plus className="h-4 w-4 mr-2" />
                Add Team
              </Button>
            </div>

            {standings.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                <Users className="h-12 w-12 mx-auto mb-2 text-gray-400" />
                <p>No teams in this league yet. Add teams to get started.</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">Pos</TableHead>
                    <TableHead>Team</TableHead>
                    <TableHead className="text-center">P</TableHead>
                    <TableHead className="text-center">W</TableHead>
                    <TableHead className="text-center">D</TableHead>
                    <TableHead className="text-center">L</TableHead>
                    <TableHead className="text-center">GF</TableHead>
                    <TableHead className="text-center">GA</TableHead>
                    <TableHead className="text-center">GD</TableHead>
                    <TableHead className="text-center">Pts</TableHead>
                    <TableHead className="w-12"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {standings
                    .sort((a: any, b: any) => {
                      if (b.points !== a.points) return b.points - a.points;
                      if (b.goalDifference !== a.goalDifference) return b.goalDifference - a.goalDifference;
                      return b.goalsFor - a.goalsFor;
                    })
                    .map((standing: any, index: number) => {
                      const team = teams.find((t) => t.id === standing.teamId);
                      return (
                        <TableRow key={standing.id} data-testid={`row-standing-${standing.teamId}`}>
                          <TableCell className="font-medium">{index + 1}</TableCell>
                          <TableCell className="font-medium">{team?.name || "Unknown"}</TableCell>
                          <TableCell className="text-center">{standing.played}</TableCell>
                          <TableCell className="text-center">{standing.won}</TableCell>
                          <TableCell className="text-center">{standing.drawn}</TableCell>
                          <TableCell className="text-center">{standing.lost}</TableCell>
                          <TableCell className="text-center">{standing.goalsFor}</TableCell>
                          <TableCell className="text-center">{standing.goalsAgainst}</TableCell>
                          <TableCell className="text-center">{standing.goalDifference}</TableCell>
                          <TableCell className="text-center font-bold">{standing.points}</TableCell>
                          <TableCell>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleRemoveTeam(standing.teamId)}
                              data-testid={`button-remove-team-${standing.teamId}`}
                            >
                              <X className="h-4 w-4 text-red-500" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                </TableBody>
              </Table>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
