import { toNumber } from "@/lib/helpers";

/**
 * The achievement tiles a profile shows, and the counters behind them.
 *
 * The fallback chains are the substance here. The same figure arrives under
 * several names depending on which endpoint served the profile —
 * `statistics.all_time.total_learn_opportunities`,
 * `total_development_opportunities`, `learn_opportunities_count` — and an
 * organization's tiles are a different set from a volunteer's. Reading the wrong
 * one shows a zero, not an error, which is why the order is preserved exactly.
 */
/**
 * Every counter any of the profile endpoints may carry.
 *
 * All optional and all `unknown`-tolerant on purpose: this is the union of
 * three resources' outputs plus the legacy names, and `toNumber` is what
 * normalises each. Listing them means a typo in a fallback chain is now a type
 * error instead of a silent zero on the profile card.
 */
export interface ProfileStatSource {
  total_opportunities?: number | string | null;
  total_volunteer_opportunities?: number | string | null;
  total_volunteer_hours?: number | string | null;
  total_learn_opportunities?: number | string | null;
  total_development_opportunities?: number | string | null;
  development_opportunities_count?: number | string | null;
  learn_opportunities_count?: number | string | null;
  learn_opportunity_organized?: number | string | null;
  vol_opportunity_organized?: number | string | null;
  opportunities_organized?: number | string | null;
  organization_hours?: number | string | null;
  sponsored?: number | string | null;
  sponsored_count?: number | string | null;
  statistics?: {
    all_time?: {
      total_opportunities?: number | string | null;
      total_volunteer_opportunities?: number | string | null;
      total_hours?: number | string | null;
      total_learn_opportunities?: number | string | null;
      total_development_opportunities?: number | string | null;
      opportunities_organized?: number | string | null;
    } | null;
  } | null;
}

export function buildProfileStatCards(
  profile: ProfileStatSource,
  t: (key: string) => string,
  userType: string | undefined,
  isVolunteerTeam: boolean
) {
  const attendedTotal = toNumber(
    profile.statistics?.all_time?.total_opportunities ??
      profile.total_opportunities
  );
  const developmentTotal = toNumber(
    profile.development_opportunities_count ??
      profile.statistics?.all_time?.total_learn_opportunities ??
      profile.statistics?.all_time?.total_development_opportunities ??
      profile.total_learn_opportunities ??
      profile.total_development_opportunities ??
      profile.learn_opportunities_count
  );
  const providedDevelopment = toNumber(
    profile.opportunities_organized ??
      profile.statistics?.all_time?.opportunities_organized
  );
  const attendedDevelopment = Math.max(
    0,
    developmentTotal - providedDevelopment
  );
  const volunteerStats = {
    hours:
      profile.statistics?.all_time?.total_hours ?? profile.total_volunteer_hours ?? 0,
    volunteerOpportunities:
      profile.statistics?.all_time?.total_volunteer_opportunities ??
      profile.total_volunteer_opportunities ??
      Math.max(0, attendedTotal - attendedDevelopment),
    developmentOpportunities:
      profile.development_opportunities_count ??
      profile.statistics?.all_time?.total_learn_opportunities ??
      profile.statistics?.all_time?.total_development_opportunities ??
      profile.total_learn_opportunities ??
      profile.total_development_opportunities ??
      profile.learn_opportunities_count ??
      0,
  };
  // `sponsored` (public-profile) vs `sponsored_count` (organization-profile).
  const sponsoredValue = profile.sponsored ?? profile.sponsored_count ?? 0;
  const organizationCards = [
    {
      icon: "profile/statistics/n_Volunteerhours.svg",
      value: profile.organization_hours ?? 0,
      label: t("COMMON.VOLUNTEER_HOURS-"),
      color: "border-primary-501 text-primary-501",
    },
    {
      icon: "profile/statistics/n_volunteer_organization.svg",
      value: profile.vol_opportunity_organized ?? 0,
      label: t("COMMON.VOLUNTEER_OPPORTUNITIES-"),
      color: "border-primary-502 text-primary-502",
    },
    {
      icon: "profile/statistics/n_learnServeicn.svg",
      value: profile.learn_opportunity_organized ?? 0,
      label: t("COMMON.OPPORTUNITIESORGANIZED--"),
      color: "border-primary-503 text-primary-503",
    },
    ...(!isVolunteerTeam
      ? [
          {
            icon: "profile/statistics/n_sponseredbyus.svg",
            value: sponsoredValue,
            label: t("COMMON.SPONSERED.ORGANIZED"),
            color: "border-primary-504 text-primary-504",
          },
        ]
      : []),
  ];
  const volunteerCards = [
    {
      icon: "profile/statistics/n_Volunteerhours.svg",
      value: volunteerStats.hours,
      label: t("COMMON.VOLUNTEER_HOURS-"),
      color: "border-primary-501 text-primary-501",
    },
    {
      icon: "profile/statistics/n_VolunteerOpportunities.svg",
      value: volunteerStats.volunteerOpportunities,
      label: t("COMMON.VOLUNTEER_OPPORTUNITIES-"),
      color: "border-primary-502 text-primary-502",
    },
    // Same card style as the entity's development counter: the icon,
    // label key and color are intentionally identical so both read as the same
    // "Development Opportunity" metric — one per learn-serve activity as
    // Participant or Provider, never a certificate count.
    {
      icon: "profile/statistics/n_learnServeicn.svg",
      value: volunteerStats.developmentOpportunities,
      label: t("COMMON.OPPORTUNITIESORGANIZED--"),
      color: "border-primary-503 text-primary-503",
    },
  ];
  /*
   * Volunteer teams are organization-like accounts (`organizer_type 21`,
   * `is_volunteer_team: true`) and keep the organization counters. Force the
   * organization set whenever the flag is on, even if a response ever labels
   * the row `user_type: "volunteer"` — otherwise a team would fall through to
   * the volunteer counters (hours/participations) which are always 0 for a
   * team and look exactly like the "all counters are 0" bug (backend never
   * reads the statistics rollup — see FURSA_BACKEND_ISSUES.md BE-55).
   */
  const cards =
    userType === "organization" || isVolunteerTeam
      ? organizationCards
      : volunteerCards;
  return { cards, volunteerStats };
}
