import { msg } from "@lingui/core/macro";
import type { I18n } from "@lingui/core";

export interface GroupConfig {
  num_groups: number;
  advance_per_group: number;
}

const wildcardMsg = msg`Wildcard {n}`;
const groupRankMsg = msg`{group} {rank, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}`;

export const formatWildcardLabel = (i18n: I18n, n: number): string =>
  i18n._({ ...wildcardMsg, values: { n } });

export const formatGroupRankLabel = (
  i18n: I18n,
  group: string,
  rank: number
): string => i18n._({ ...groupRankMsg, values: { group, rank } });

export function getGroupLabel(
  i18n: I18n,
  seed: number | undefined,
  groupConfig: GroupConfig | undefined
): string | undefined {
  if (!seed || !groupConfig) return undefined;

  const groupNames = ["A", "B", "C", "D", "E", "F", "G", "H"];
  const numGroups = groupConfig.num_groups;
  const advancePerGroup = groupConfig.advance_per_group;

  const totalQualifiedTeams = numGroups * advancePerGroup;
  const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(totalQualifiedTeams)));
  const wildcardsNeeded = nextPowerOf2 - totalQualifiedTeams;

  if (seed > totalQualifiedTeams && wildcardsNeeded > 0) {
    const wildcardNumber = seed - totalQualifiedTeams;
    return formatWildcardLabel(i18n, wildcardNumber);
  }

  const pairIndex = Math.floor((seed - 1) / 2);
  const isFirstInPair = (seed - 1) % 2 === 0;

  if (isFirstInPair) {
    const groupIndex = pairIndex % numGroups;
    const rankIndex = Math.floor(pairIndex / numGroups);

    const rank = rankIndex + 1;
    const groupName = groupNames[groupIndex] || `${groupIndex + 1}`;

    return formatGroupRankLabel(i18n, groupName, rank);
  } else {
    const groupIndex = (pairIndex + 1) % numGroups;
    const rankIndex = advancePerGroup - 1 - Math.floor(pairIndex / numGroups);

    const rank = rankIndex + 1;
    const groupName = groupNames[groupIndex] || `${groupIndex + 1}`;

    return formatGroupRankLabel(i18n, groupName, rank);
  }
}
