import React from "react";
import { useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { 
  Users, 
  User, 
  UserCheck, 
  UserX, 
  UserMinus, 
  Trophy,
  Calendar,
  MapPin,
  Phone,
  Mail,
  Award
} from "lucide-react";
import type { Team, Player } from "@shared/schema";

interface TeamDetailModalProps {
  team: Team | null;
  isOpen: boolean;
  onClose: () => void;
}

export default function TeamDetailModal({ team, isOpen, onClose }: TeamDetailModalProps) {
  const { data: players = [] } = useQuery({
    queryKey: ["/api/players"],
    enabled: isOpen && !!team,
  });

  if (!team) return null;

  // Filter players for this team
  const teamPlayers = players.filter((player: Player) => player.teamId === team.id);

  // Organize players by gender and status
  const maleActive = teamPlayers.filter((p: Player) => p.gender === "male" && p.status === "active");
  const maleInactive = teamPlayers.filter((p: Player) => p.gender === "male" && p.status === "inactive");
  const maleSuspended = teamPlayers.filter((p: Player) => p.gender === "male" && p.status === "suspended");
  
  const femaleActive = teamPlayers.filter((p: Player) => p.gender === "female" && p.status === "active");
  const femaleInactive = teamPlayers.filter((p: Player) => p.gender === "female" && p.status === "inactive");
  const femaleSuspended = teamPlayers.filter((p: Player) => p.gender === "female" && p.status === "suspended");

  const PlayerCard = ({ player }: { player: Player }) => (
    <div className="flex items-center space-x-3 p-3 border rounded-lg bg-white hover:bg-gray-50 transition-colors">
      <Avatar className="h-10 w-10">
        <AvatarImage src={player.profileImageUrl} />
        <AvatarFallback className="bg-primary/10 text-primary font-semibold">
          {player.firstName[0]}{player.lastName[0]}
        </AvatarFallback>
      </Avatar>
      <div className="flex-1 min-w-0">
        <p className="font-medium text-gray-900 truncate">
          {player.firstName} {player.lastName}
        </p>
        <p className="text-sm text-gray-500">
          {player.position} • #{player.jerseyNumber}
        </p>
      </div>
      <Badge 
        variant={player.status === "active" ? "default" : player.status === "inactive" ? "secondary" : "destructive"}
        className="text-xs"
      >
        {player.status}
      </Badge>
    </div>
  );

  const PlayerSection = ({ 
    title, 
    players, 
    icon: Icon, 
    emptyMessage 
  }: { 
    title: string; 
    players: Player[]; 
    icon: React.ComponentType<any>; 
    emptyMessage: string; 
  }) => (
    <div className="space-y-3">
      <div className="flex items-center space-x-2">
        <Icon className="h-4 w-4 text-gray-600" />
        <h4 className="font-semibold text-gray-900">{title}</h4>
        <Badge variant="outline" className="ml-auto">
          {players.length}
        </Badge>
      </div>
      {players.length > 0 ? (
        <div className="space-y-2">
          {players.map((player) => (
            <PlayerCard key={player.id} player={player} />
          ))}
        </div>
      ) : (
        <p className="text-sm text-gray-500 italic py-4 text-center border-2 border-dashed border-gray-200 rounded-lg">
          {emptyMessage}
        </p>
      )}
    </div>
  );

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-3">
            <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center">
              <Trophy className="h-6 w-6 text-primary" />
            </div>
            <div>
              <h2 className="text-2xl font-bold">{team.name}</h2>
              <p className="text-sm text-gray-500 capitalize">{team.sport} Team</p>
            </div>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* Team Overview */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Users className="h-5 w-5" />
                <span>Team Overview</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-gray-700">{team.description}</p>
              
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="text-center p-3 bg-blue-50 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">{teamPlayers.length}</div>
                  <div className="text-sm text-blue-700">Total Players</div>
                </div>
                <div className="text-center p-3 bg-green-50 rounded-lg">
                  <div className="text-2xl font-bold text-green-600">
                    {teamPlayers.filter(p => p.status === "active").length}
                  </div>
                  <div className="text-sm text-green-700">Active Players</div>
                </div>
                <div className="text-center p-3 bg-purple-50 rounded-lg">
                  <div className="text-2xl font-bold text-purple-600">
                    {teamPlayers.filter(p => p.gender === "male").length}
                  </div>
                  <div className="text-sm text-purple-700">Male Players</div>
                </div>
                <div className="text-center p-3 bg-pink-50 rounded-lg">
                  <div className="text-2xl font-bold text-pink-600">
                    {teamPlayers.filter(p => p.gender === "female").length}
                  </div>
                  <div className="text-sm text-pink-700">Female Players</div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Male Players */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <User className="h-5 w-5 text-blue-600" />
                <span>Male Players</span>
                <Badge variant="outline" className="ml-auto">
                  {maleActive.length + maleInactive.length + maleSuspended.length}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <PlayerSection
                title="Active Players"
                players={maleActive}
                icon={UserCheck}
                emptyMessage="No active male players"
              />
              
              {(maleInactive.length > 0 || maleSuspended.length > 0) && <Separator />}
              
              {maleInactive.length > 0 && (
                <PlayerSection
                  title="Inactive Players"
                  players={maleInactive}
                  icon={UserMinus}
                  emptyMessage="No inactive male players"
                />
              )}
              
              {maleSuspended.length > 0 && (
                <>
                  {maleInactive.length > 0 && <Separator />}
                  <PlayerSection
                    title="Suspended Players"
                    players={maleSuspended}
                    icon={UserX}
                    emptyMessage="No suspended male players"
                  />
                </>
              )}
            </CardContent>
          </Card>

          {/* Female Players */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <User className="h-5 w-5 text-pink-600" />
                <span>Female Players</span>
                <Badge variant="outline" className="ml-auto">
                  {femaleActive.length + femaleInactive.length + femaleSuspended.length}
                </Badge>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <PlayerSection
                title="Active Players"
                players={femaleActive}
                icon={UserCheck}
                emptyMessage="No active female players"
              />
              
              {(femaleInactive.length > 0 || femaleSuspended.length > 0) && <Separator />}
              
              {femaleInactive.length > 0 && (
                <PlayerSection
                  title="Inactive Players"
                  players={femaleInactive}
                  icon={UserMinus}
                  emptyMessage="No inactive female players"
                />
              )}
              
              {femaleSuspended.length > 0 && (
                <>
                  {femaleInactive.length > 0 && <Separator />}
                  <PlayerSection
                    title="Suspended Players"
                    players={femaleSuspended}
                    icon={UserX}
                    emptyMessage="No suspended female players"
                  />
                </>
              )}
            </CardContent>
          </Card>
        </div>
      </DialogContent>
    </Dialog>
  );
}