import { normalizePdfText } from '@/components/pdf/pdfUtils';

import { isStateAward } from '@/utils/awardHelpers';

import { CreatorAward } from '@/types/Award';

export type CreatorAwardPdfItem = {
  description: string;
  key: string;
  title: string;
  typeLabel: string;
  yearLabel: string;
};

export type CreatorAwardPdfGroup = {
  awards: CreatorAwardPdfItem[];
  groupLabel: string;
  isStateGroup: boolean;
};

type BuildCreatorAwardPdfGroupsOptions = {
  otherGroupLabel: string;
  stateGroupLabel: string;
};

// Newest first; awards without a year sink to the bottom — mirrors the on-page
// ordering in CreatorAwardsSection.
const byYearDesc = (a: CreatorAward, b: CreatorAward): number => {
  if (a.ev == null) return 1;
  if (b.ev == null) return -1;
  return b.ev - a.ev;
};

const toPdfItem = (award: CreatorAward, index: number): CreatorAwardPdfItem => ({
  description: normalizePdfText(award.leiras),
  key: `${award.id ?? award.nev ?? 'award'}-${award.ev ?? 'na'}-${index}`,
  title: normalizePdfText(award.nev),
  typeLabel: normalizePdfText(award.dijazasTipusaNev),
  yearLabel: award.ev != null ? String(award.ev) : '',
});

export const buildCreatorAwardPdfGroups = (
  awards: CreatorAward[],
  { otherGroupLabel, stateGroupLabel }: BuildCreatorAwardPdfGroupsOptions
): CreatorAwardPdfGroup[] => {
  // State awards read as their own block (as on the profile page); everything
  // else is grouped together.
  const stateAwards = awards.filter((award) => isStateAward(award.dijazasTipusaId)).sort(byYearDesc);
  const otherAwards = awards
    .filter((award) => !isStateAward(award.dijazasTipusaId))
    .sort(byYearDesc);

  const groups: CreatorAwardPdfGroup[] = [];

  if (stateAwards.length > 0) {
    groups.push({ groupLabel: stateGroupLabel, awards: stateAwards.map(toPdfItem), isStateGroup: true });
  }
  if (otherAwards.length > 0) {
    groups.push({ groupLabel: otherGroupLabel, awards: otherAwards.map(toPdfItem), isStateGroup: false });
  }

  return groups;
};
