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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
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, Calendar, MapPin, Users, Clock, Trophy, Activity, TrendingUp, Eye } from "lucide-react";
import type { Fixture, League, Team, Venue, Referee, MatchEvent, MatchStatistics } 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 fixtureFormSchema = z.object({
  leagueId: z.number().optional(),
  tournamentId: z.number().optional(),
  homeTeamId: z.number({ required_error: "Home team is required" }),
  awayTeamId: z.number({ required_error: "Away team is required" }),
  venueId: z.number().optional(),
  refereeId: z.number().optional(),
  scheduledDate: z.string(),
  kickoffTime: z.string(),
  status: z.string().default("scheduled"),
  homeScore: z.number().optional(),
  awayScore: z.number().optional(),
  attendance: z.number().optional(),
  notes: z.string().optional(),
});

type FixtureFormValues = z.infer<typeof fixtureFormSchema>;

const matchEventSchema = z.object({
  eventType: z.string(),
  teamId: z.number(),
  playerId: z.number().optional(),
  minute: z.number(),
  description: z.string().optional(),
});

export default function Fixtures() {
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [leagueFilter, setLeagueFilter] = useState<string>("all");
  const [selectedFixture, setSelectedFixture] = useState<Fixture | null>(null);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [showMatchDetailsDialog, setShowMatchDetailsDialog] = useState(false);
  const [activeTab, setActiveTab] = useState("all");
  const { toast } = useToast();
  const queryClient = useQueryClient();

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

  const { data: upcomingFixtures = [] } = useQuery<Fixture[]>({
    queryKey: ["/api/fixtures/upcoming"],
  });

  const { data: liveFixtures = [] } = useQuery<Fixture[]>({
    queryKey: ["/api/fixtures/live"],
    refetchInterval: 30000, // Refresh every 30 seconds
  });

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

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

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

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

  const { data: matchEvents = [] } = useQuery<MatchEvent[]>({
    queryKey: selectedFixture ? [`/api/fixtures/${selectedFixture.id}/events`] : [],
    enabled: !!selectedFixture,
  });

  const { data: matchStats = [] } = useQuery<MatchStatistics[]>({
    queryKey: selectedFixture ? [`/api/fixtures/${selectedFixture.id}/statistics`] : [],
    enabled: !!selectedFixture,
  });

  const form = useForm<FixtureFormValues>({
    resolver: zodResolver(fixtureFormSchema),
    defaultValues: {
      status: "scheduled",
      kickoffTime: "15:00",
    },
  });

  const createFixtureMutation = useMutation({
    mutationFn: async (data: FixtureFormValues) => {
      await apiRequest("POST", "/api/fixtures", {
        ...data,
        scheduledDate: new Date(data.scheduledDate).toISOString(),
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures"] });
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures/upcoming"] });
      setShowCreateDialog(false);
      form.reset();
      toast({
        title: "Success",
        description: "Fixture created successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to create fixture",
        variant: "destructive",
      });
    },
  });

  const updateFixtureMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: Partial<FixtureFormValues> }) => {
      await apiRequest("PUT", `/api/fixtures/${id}`, {
        ...data,
        scheduledDate: data.scheduledDate ? new Date(data.scheduledDate).toISOString() : undefined,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures"] });
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures/upcoming"] });
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures/live"] });
      setShowEditDialog(false);
      setSelectedFixture(null);
      toast({
        title: "Success",
        description: "Fixture updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update fixture",
        variant: "destructive",
      });
    },
  });

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

  const updateMatchResultMutation = useMutation({
    mutationFn: async ({ id, homeScore, awayScore, status }: { id: number; homeScore: number; awayScore: number; status: string }) => {
      await apiRequest("PUT", `/api/fixtures/${id}`, { 
        homeScore, 
        awayScore, 
        status,
        halfTimeHomeScore: Math.floor(homeScore / 2),
        halfTimeAwayScore: Math.floor(awayScore / 2),
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures"] });
      queryClient.invalidateQueries({ queryKey: ["/api/fixtures/live"] });
      toast({
        title: "Success",
        description: "Match result updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.message || "Failed to update match result",
        variant: "destructive",
      });
    },
  });

  const getFilteredFixtures = () => {
    let filtered = fixtures || [];

    if (activeTab === "upcoming") {
      filtered = upcomingFixtures;
    } else if (activeTab === "live") {
      filtered = liveFixtures;
    }

    return filtered.filter((fixture) => {
      const homeTeam = teams.find((t) => t.id === fixture.homeTeamId);
      const awayTeam = teams.find((t) => t.id === fixture.awayTeamId);

      const matchesSearch =
        homeTeam?.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        awayTeam?.name.toLowerCase().includes(searchQuery.toLowerCase());

      const matchesStatus = statusFilter === "all" || fixture.status === statusFilter;
      const matchesLeague = leagueFilter === "all" || fixture.leagueId?.toString() === leagueFilter;

      return matchesSearch && matchesStatus && matchesLeague;
    });
  };

  const handleEdit = (fixture: Fixture) => {
    setSelectedFixture(fixture);
    const schedDate = new Date(fixture.scheduledDate).toISOString().split('T')[0];
    form.reset({
      leagueId: fixture.leagueId || undefined,
      tournamentId: fixture.tournamentId || undefined,
      homeTeamId: fixture.homeTeamId,
      awayTeamId: fixture.awayTeamId,
      venueId: fixture.venueId || undefined,
      refereeId: fixture.refereeId || undefined,
      scheduledDate: schedDate,
      kickoffTime: fixture.kickoffTime,
      status: fixture.status,
      homeScore: fixture.homeScore || undefined,
      awayScore: fixture.awayScore || undefined,
      attendance: fixture.attendance || undefined,
      notes: fixture.notes || "",
    });
    setShowEditDialog(true);
  };

  const handleDelete = async (fixtureId: number) => {
    if (window.confirm("Are you sure you want to delete this fixture? This will also remove all match events and statistics.")) {
      deleteFixtureMutation.mutate(fixtureId);
    }
  };

  const handleViewDetails = (fixture: Fixture) => {
    setSelectedFixture(fixture);
    setShowMatchDetailsDialog(true);
  };

  const handleUpdateScore = (fixture: Fixture, homeScore: number, awayScore: number) => {
    updateMatchResultMutation.mutate({
      id: fixture.id,
      homeScore,
      awayScore,
      status: "completed",
    });
  };

  const onSubmit = (data: FixtureFormValues) => {
    if (data.homeTeamId === data.awayTeamId) {
      toast({
        title: "Error",
        description: "Home and away teams must be different",
        variant: "destructive",
      });
      return;
    }

    if (selectedFixture) {
      updateFixtureMutation.mutate({ id: selectedFixture.id, data });
    } else {
      createFixtureMutation.mutate(data);
    }
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "live":
        return "default";
      case "completed":
        return "secondary";
      case "postponed":
        return "destructive";
      case "cancelled":
        return "destructive";
      default:
        return "outline";
    }
  };

  const filteredFixtures = getFilteredFixtures();

  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 fixtures...</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" />
            Fixtures & Matches
          </h1>
          <p className="text-gray-600 mt-2">Manage match schedules, results, and live updates</p>
        </div>
        <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
          <DialogTrigger asChild>
            <Button data-testid="button-create-fixture">
              <Plus className="h-4 w-4 mr-2" />
              Schedule Match
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Schedule New Match</DialogTitle>
              <DialogDescription>Create a new fixture for a league or tournament</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="leagueId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>League (Optional)</FormLabel>
                        <Select
                          value={field.value?.toString() || ""}
                          onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                        >
                          <FormControl>
                            <SelectTrigger data-testid="select-league">
                              <SelectValue placeholder="Select league" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="">No League</SelectItem>
                            {leagues.map((league) => (
                              <SelectItem key={league.id} value={league.id.toString()}>
                                {league.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="venueId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Venue (Optional)</FormLabel>
                        <Select
                          value={field.value?.toString() || ""}
                          onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                        >
                          <FormControl>
                            <SelectTrigger data-testid="select-venue">
                              <SelectValue placeholder="Select venue" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value="">No Venue</SelectItem>
                            {venues.map((venue) => (
                              <SelectItem key={venue.id} value={venue.id.toString()}>
                                {venue.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="homeTeamId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Home Team</FormLabel>
                        <Select
                          value={field.value?.toString() || ""}
                          onValueChange={(value) => field.onChange(parseInt(value))}
                        >
                          <FormControl>
                            <SelectTrigger data-testid="select-home-team">
                              <SelectValue placeholder="Select home team" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {teams.map((team) => (
                              <SelectItem key={team.id} value={team.id.toString()}>
                                {team.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="awayTeamId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Away Team</FormLabel>
                        <Select
                          value={field.value?.toString() || ""}
                          onValueChange={(value) => field.onChange(parseInt(value))}
                        >
                          <FormControl>
                            <SelectTrigger data-testid="select-away-team">
                              <SelectValue placeholder="Select away team" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {teams.map((team) => (
                              <SelectItem key={team.id} value={team.id.toString()}>
                                {team.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="scheduledDate"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Match Date</FormLabel>
                        <FormControl>
                          <Input type="date" {...field} data-testid="input-date" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="kickoffTime"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Kickoff Time</FormLabel>
                        <FormControl>
                          <Input type="time" {...field} data-testid="input-time" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={form.control}
                  name="refereeId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Referee (Optional)</FormLabel>
                      <Select
                        value={field.value?.toString() || ""}
                        onValueChange={(value) => field.onChange(value ? parseInt(value) : undefined)}
                      >
                        <FormControl>
                          <SelectTrigger data-testid="select-referee">
                            <SelectValue placeholder="Select referee" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="">No Referee</SelectItem>
                          {referees.map((referee) => (
                            <SelectItem key={referee.id} value={referee.id.toString()}>
                              {referee.firstName} {referee.lastName}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="notes"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Notes (Optional)</FormLabel>
                      <FormControl>
                        <Textarea {...field} placeholder="Any additional information..." data-testid="input-notes" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <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={createFixtureMutation.isPending} data-testid="button-submit">
                    {createFixtureMutation.isPending ? "Creating..." : "Schedule Match"}
                  </Button>
                </div>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
        <TabsList>
          <TabsTrigger value="all" data-testid="tab-all">All Fixtures</TabsTrigger>
          <TabsTrigger value="live" className="flex items-center gap-2" data-testid="tab-live">
            <Activity className="h-4 w-4" />
            Live ({liveFixtures.length})
          </TabsTrigger>
          <TabsTrigger value="upcoming" data-testid="tab-upcoming">Upcoming</TabsTrigger>
        </TabsList>
      </Tabs>

      <div className="flex flex-col md:flex-row gap-4 mb-6">
        <div className="flex-1 relative">
          <Input
            placeholder="Search fixtures by team name..."
            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="scheduled">Scheduled</SelectItem>
            <SelectItem value="live">Live</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="postponed">Postponed</SelectItem>
            <SelectItem value="cancelled">Cancelled</SelectItem>
          </SelectContent>
        </Select>
        <Select value={leagueFilter} onValueChange={setLeagueFilter}>
          <SelectTrigger className="w-full md:w-48" data-testid="select-league-filter">
            <SelectValue placeholder="All Leagues" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Leagues</SelectItem>
            {leagues.map((league) => (
              <SelectItem key={league.id} value={league.id.toString()}>
                {league.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {filteredFixtures.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16">
            <Calendar className="h-16 w-16 text-gray-400 mb-4" />
            <h3 className="text-xl font-semibold text-gray-700 mb-2">No fixtures found</h3>
            <p className="text-gray-500 mb-4">
              {searchQuery || statusFilter !== "all" || leagueFilter !== "all"
                ? "Try adjusting your filters"
                : "Get started by scheduling your first match"}
            </p>
            {!searchQuery && statusFilter === "all" && leagueFilter === "all" && (
              <Button onClick={() => setShowCreateDialog(true)} data-testid="button-create-first">
                <Plus className="h-4 w-4 mr-2" />
                Schedule Match
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 gap-4">
          {filteredFixtures.map((fixture) => {
            const homeTeam = teams.find((t) => t.id === fixture.homeTeamId);
            const awayTeam = teams.find((t) => t.id === fixture.awayTeamId);
            const venue = venues.find((v) => v.id === fixture.venueId);
            const league = leagues.find((l) => l.id === fixture.leagueId);

            return (
              <Card key={fixture.id} className="hover:shadow-lg transition-shadow" data-testid={`card-fixture-${fixture.id}`}>
                <CardContent className="p-6">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-4">
                        {league && (
                          <Badge variant="outline">
                            {league.name}
                          </Badge>
                        )}
                        <Badge variant={getStatusBadgeVariant(fixture.status)}>
                          {fixture.status}
                        </Badge>
                        <span className="text-sm text-gray-500">
                          {new Date(fixture.scheduledDate).toLocaleDateString()} • {fixture.kickoffTime}
                        </span>
                      </div>

                      <div className="grid grid-cols-3 gap-4 items-center mb-4">
                        <div className="text-right">
                          <h3 className="text-lg font-semibold">{homeTeam?.name || "Unknown"}</h3>
                        </div>
                        <div className="text-center">
                          {fixture.status === "completed" || fixture.homeScore !== null ? (
                            <div className="text-3xl font-bold">
                              {fixture.homeScore ?? 0} - {fixture.awayScore ?? 0}
                            </div>
                          ) : (
                            <div className="text-xl font-semibold text-gray-400">vs</div>
                          )}
                        </div>
                        <div className="text-left">
                          <h3 className="text-lg font-semibold">{awayTeam?.name || "Unknown"}</h3>
                        </div>
                      </div>

                      {venue && (
                        <div className="flex items-center text-sm text-gray-600 mb-2">
                          <MapPin className="h-4 w-4 mr-2" />
                          {venue.name}
                        </div>
                      )}

                      {fixture.attendance && (
                        <div className="flex items-center text-sm text-gray-600">
                          <Users className="h-4 w-4 mr-2" />
                          {fixture.attendance.toLocaleString()} attendees
                        </div>
                      )}
                    </div>

                    <div className="flex gap-2 ml-4">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleViewDetails(fixture)}
                        data-testid={`button-details-${fixture.id}`}
                      >
                        <Eye className="h-4 w-4 mr-1" />
                        Details
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEdit(fixture)}
                        data-testid={`button-edit-${fixture.id}`}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDelete(fixture.id)}
                        data-testid={`button-delete-${fixture.id}`}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Edit Fixture Dialog */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Fixture</DialogTitle>
            <DialogDescription>Update fixture information and match result</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="homeScore"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Home Score</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                          data-testid="input-home-score"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="awayScore"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Away Score</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          {...field}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                          data-testid="input-away-score"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <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="scheduled">Scheduled</SelectItem>
                        <SelectItem value="live">Live</SelectItem>
                        <SelectItem value="completed">Completed</SelectItem>
                        <SelectItem value="postponed">Postponed</SelectItem>
                        <SelectItem value="cancelled">Cancelled</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="attendance"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Attendance</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        {...field}
                        onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                        data-testid="input-attendance"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

      {/* Match Details Dialog */}
      <Dialog open={showMatchDetailsDialog} onOpenChange={setShowMatchDetailsDialog}>
        <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" />
              Match Details
            </DialogTitle>
            <DialogDescription>Events, statistics, and match information</DialogDescription>
          </DialogHeader>

          {selectedFixture && (
            <div className="space-y-6">
              <div className="grid grid-cols-3 gap-4 items-center p-4 bg-gray-50 rounded-lg">
                <div className="text-right">
                  <h3 className="text-xl font-bold">{teams.find((t) => t.id === selectedFixture.homeTeamId)?.name}</h3>
                </div>
                <div className="text-center">
                  <div className="text-4xl font-bold">
                    {selectedFixture.homeScore ?? 0} - {selectedFixture.awayScore ?? 0}
                  </div>
                </div>
                <div className="text-left">
                  <h3 className="text-xl font-bold">{teams.find((t) => t.id === selectedFixture.awayTeamId)?.name}</h3>
                </div>
              </div>

              <Tabs defaultValue="events">
                <TabsList className="w-full">
                  <TabsTrigger value="events" className="flex-1">Match Events</TabsTrigger>
                  <TabsTrigger value="statistics" className="flex-1">Statistics</TabsTrigger>
                </TabsList>

                <TabsContent value="events" className="space-y-4">
                  {matchEvents.length === 0 ? (
                    <p className="text-center py-8 text-gray-500">No match events recorded yet</p>
                  ) : (
                    <div className="space-y-2">
                      {matchEvents.map((event) => {
                        const team = teams.find((t) => t.id === event.teamId);
                        return (
                          <div
                            key={event.id}
                            className="flex items-center justify-between p-3 bg-gray-50 rounded"
                            data-testid={`event-${event.id}`}
                          >
                            <div className="flex items-center gap-3">
                              <Badge variant="outline">{event.minute}'</Badge>
                              <span className="font-medium">{event.eventType}</span>
                              <span className="text-gray-600">{team?.name}</span>
                            </div>
                            {event.description && (
                              <span className="text-sm text-gray-500">{event.description}</span>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="statistics">
                  {matchStats.length === 0 ? (
                    <p className="text-center py-8 text-gray-500">No match statistics recorded yet</p>
                  ) : (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Statistic</TableHead>
                          <TableHead className="text-center">Home</TableHead>
                          <TableHead className="text-center">Away</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {["possession", "shots", "shotsOnTarget", "corners", "fouls", "yellowCards", "redCards"].map((stat) => {
                          const homeStat = matchStats.find((s) => s.teamId === selectedFixture.homeTeamId);
                          const awayStat = matchStats.find((s) => s.teamId === selectedFixture.awayTeamId);
                          const homeValue = homeStat?.[stat as keyof MatchStatistics];
                          const awayValue = awayStat?.[stat as keyof MatchStatistics];
                          return (
                            <TableRow key={stat}>
                              <TableCell className="font-medium capitalize">
                                {stat.replace(/([A-Z])/g, " $1").trim()}
                              </TableCell>
                              <TableCell className="text-center">
                                {typeof homeValue === 'number' ? homeValue : 0}
                              </TableCell>
                              <TableCell className="text-center">
                                {typeof awayValue === 'number' ? awayValue : 0}
                              </TableCell>
                            </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  )}
                </TabsContent>
              </Tabs>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
