import type { GroupStandingsRow } from "~/models/group-stage-match";
import { TeamOwnerBadge } from "~/components/ui/team-owner-badge";

interface GroupMatch {
  id: string;
  matchday: number;
  scheduledAt: string | null;
  isComplete: boolean;
  participant1Id: string;
  participant2Id: string;
  participant1Score: number | null;
  participant2Score: number | null;
  participant1: { id: string; name: string } | null;
  participant2: { id: string; name: string } | null;
}

interface GroupData {
  groupName: string;
  standings: GroupStandingsRow[];
  matches: GroupMatch[];
}

interface OwnerInfo {
  teamName: string;
  ownerName: string;
  teamId: string;
}

interface GroupStageStandingsProps {
  groups: GroupData[];
  /** participantId → owner info, used to show which manager drafted each team */
  ownershipMap?: Record<string, OwnerInfo>;
  /** If true, shows all groups. If false, shows only groups with at least one completed match. */
  showEmpty?: boolean;
}

function MatchResult({ match }: { match: GroupMatch }) {
  const p1 = match.participant1?.name ?? "?";
  const p2 = match.participant2?.name ?? "?";

  if (match.isComplete && match.participant1Score !== null && match.participant2Score !== null) {
    const s1 = match.participant1Score;
    const s2 = match.participant2Score;
    const result = s1 > s2 ? "w" : s1 < s2 ? "l" : "d";
    return (
      <div className="flex items-center gap-1 text-xs text-muted-foreground">
        <span
          className={`truncate max-w-[80px] ${result === "w" ? "font-semibold text-foreground" : ""}`}
        >
          {p1}
        </span>
        <span className="shrink-0 font-mono font-semibold text-foreground tabular-nums">
          {s1}–{s2}
        </span>
        <span
          className={`truncate max-w-[80px] text-right ${result === "l" ? "font-semibold text-foreground" : ""}`}
        >
          {p2}
        </span>
      </div>
    );
  }

  const kickoff = match.scheduledAt ? new Date(match.scheduledAt) : null;
  return (
    <div className="flex items-center gap-1 text-xs text-muted-foreground">
      <span className="truncate max-w-[80px]">{p1}</span>
      <span className="shrink-0 text-muted-foreground/60">
        {kickoff
          ? kickoff.toLocaleDateString("en-US", { month: "short", day: "numeric" })
          : "vs"}
      </span>
      <span className="truncate max-w-[80px] text-right">{p2}</span>
    </div>
  );
}

export function GroupStageStandings({
  groups,
  ownershipMap,
  showEmpty = false,
}: GroupStageStandingsProps) {
  const visibleGroups = showEmpty
    ? groups
    : groups.filter((g) => g.matches.some((m) => m.isComplete) || g.standings.length > 0);

  if (visibleGroups.length === 0) return null;

  return (
    <div className="space-y-4">
      <h3 className="text-lg font-semibold">Group Stage</h3>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {groups.map((group) => (
          <div
            key={group.groupName}
            className="rounded-lg border bg-card text-card-foreground shadow-sm overflow-hidden"
          >
            {/* Header */}
            <div className="px-4 py-2 bg-muted/50 border-b">
              <h4 className="text-sm font-semibold">Group {group.groupName}</h4>
            </div>

            {/* Standings table */}
            <div className="px-4 pt-3 pb-2">
              <table className="w-full text-xs">
                <thead>
                  <tr className="text-muted-foreground border-b">
                    <th className="text-left pb-1 font-medium">Team</th>
                    <th className="text-left pb-1 font-medium">Manager</th>
                    <th className="text-center pb-1 font-medium w-6" title="Played">P</th>
                    <th className="text-center pb-1 font-medium w-6" title="Wins">W</th>
                    <th className="text-center pb-1 font-medium w-6" title="Draws">D</th>
                    <th className="text-center pb-1 font-medium w-6" title="Losses">L</th>
                    <th className="text-center pb-1 font-medium w-8" title="Goal Difference">GD</th>
                    <th className="text-center pb-1 font-medium w-7" title="Points">Pts</th>
                  </tr>
                </thead>
                <tbody>
                  {group.standings.map((row, idx) => {
                    const owner = ownershipMap?.[row.participantId];
                    return (
                      <tr
                        key={row.participantId}
                        className={`border-b last:border-0 ${
                          idx < 2
                            ? "text-green-700 dark:text-green-400"
                            : "text-muted-foreground"
                        }`}
                      >
                        <td className="py-1 font-medium text-foreground">
                          <span className="truncate block">
                            {row.participantName}
                            {idx < 2 && (
                              <span className="ml-1 text-green-600 dark:text-green-400 text-[10px]">↑</span>
                            )}
                          </span>
                        </td>
                        <td className="py-1">
                          {owner
                            ? <TeamOwnerBadge teamName={owner.teamName} ownerName={owner.ownerName} />
                            : <span className="text-xs text-muted-foreground/50">—</span>
                          }
                        </td>
                        <td className="text-center tabular-nums">{row.played}</td>
                        <td className="text-center tabular-nums">{row.wins}</td>
                        <td className="text-center tabular-nums">{row.draws}</td>
                        <td className="text-center tabular-nums">{row.losses}</td>
                        <td className="text-center tabular-nums">
                          {row.gd > 0 ? `+${row.gd}` : row.gd}
                        </td>
                        <td className="text-center tabular-nums font-semibold text-foreground">
                          {row.points}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            {/* Match results */}
            {group.matches.length > 0 && (
              <div className="px-4 pb-3 space-y-0.5 border-t pt-2">
                {[1, 2, 3].map((day) => {
                  const dayMatches = group.matches.filter((m) => m.matchday === day);
                  if (dayMatches.length === 0) return null;
                  return (
                    <div key={day} className="space-y-0.5">
                      <p className="text-[10px] text-muted-foreground/70 uppercase tracking-wide pt-1">
                        MD {day}
                      </p>
                      {dayMatches.map((m) => (
                        <MatchResult key={m.id} match={m} />
                      ))}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
