import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { Badge } from "~/components/ui/badge";
import { Users } from "lucide-react";
import { getAvatarColor } from "~/lib/color-hash";

interface GroupMember {
  id: string;
  eliminated: boolean;
  participant: {
    id: string;
    name: string;
  } | null;
}

interface TournamentGroup {
  id: string;
  groupName: string;
  members: GroupMember[];
}

interface TeamOwnership {
  participantId: string;
  teamName: string;
  teamId: string;
  ownerName?: string;
}

interface GroupStageDisplayProps {
  groups: TournamentGroup[];
  teamOwnerships?: TeamOwnership[];
  showOwnership?: boolean;
  title?: string;
  description?: string;
}

/**
 * Read-only display of tournament group stage for league-facing pages.
 * Shows groups in a responsive card grid with eliminated status indicators.
 */
export function GroupStageDisplay({
  groups,
  teamOwnerships = [],
  showOwnership = true,
  title = "Group Stage",
  description,
}: GroupStageDisplayProps) {
  const ownershipMap = new Map<string, TeamOwnership>();
  teamOwnerships.forEach((o) => ownershipMap.set(o.participantId, o));

  const getTeamAvatar = (teamName: string) => (
    <div
      className={`h-6 w-6 rounded-full ${getAvatarColor(teamName)} text-white text-xs font-bold flex items-center justify-center`}
    >
      {teamName.charAt(0).toUpperCase()}
    </div>
  );

  const totalTeams = groups.reduce((sum, g) => sum + g.members.length, 0);
  const eliminatedCount = groups.reduce(
    (sum, g) => sum + g.members.filter((m) => m.eliminated).length,
    0
  );

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Users className="h-5 w-5" />
          {title}
        </CardTitle>
        {description && <CardDescription>{description}</CardDescription>}
        <div className="flex gap-2 mt-2">
          <Badge variant="secondary">{totalTeams} teams</Badge>
          {eliminatedCount > 0 && (
            <Badge variant="destructive">{eliminatedCount} eliminated</Badge>
          )}
          <Badge variant="default">{totalTeams - eliminatedCount} advancing</Badge>
        </div>
      </CardHeader>
      <CardContent>
        {groups.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            <p className="text-sm">No group stage data available yet.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            {groups.map((group) => (
              <Card key={group.id} className="border-dashed">
                <CardHeader className="py-3 px-4">
                  <CardTitle className="text-base">Group {group.groupName}</CardTitle>
                </CardHeader>
                <CardContent className="px-4 pb-4 space-y-1.5">
                  {group.members.map((member) => {
                    const ownership =
                      showOwnership && member.participant
                        ? ownershipMap.get(member.participant.id)
                        : null;

                    return (
                      <div
                        key={member.id}
                        className={`flex items-center justify-between gap-2 px-2 py-1.5 rounded-md ${
                          member.eliminated
                            ? "bg-destructive/10 text-muted-foreground"
                            : ""
                        }`}
                      >
                        <span
                          className={`text-sm truncate ${
                            member.eliminated ? "line-through" : "font-medium"
                          }`}
                        >
                          {member.participant?.name || "Unknown"}
                        </span>
                        {ownership && (
                          <div
                            className="cursor-help shrink-0"
                            title={`${ownership.teamName}${ownership.ownerName ? ` (${ownership.ownerName})` : ""}`}
                          >
                            {getTeamAvatar(ownership.teamName)}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
