import type { CounterVisibility } from "@/features/profile/accountRecords";

import type { ArabicNumeric } from "@/features/shared/apiPrimitives";

/**
 * The public-profile payload, its tabs, and three small helpers.
 *
 * `isCertificateItem` is a type guard rather than a cast: the certificates array
 * comes back loosely typed and a row missing its image would otherwise render an
 * `<img>` with `src={undefined}`.
 */
/**
 * A `*_display` choice as a website resource emits it.
 *
 * `value_en`/`value_ar` are `string | null | undefined`, all three:
 * `websiteChoicePayload()` drops a null key outright (so the field can be
 * *absent*), while `websiteInterestDisplay()` emits `value_en ?? name_en`,
 * which is *null* when both columns are empty. Every reader goes through
 * `?? ""`.
 */
export interface LocalizedValue {
  /** Optional *and* nullable: `websiteInterestDisplay()` emits no `id` at all,
      while `masterChoicePayload()` can emit a null one. */
  id?: string | number | null;
  value_en?: string | null;
  value_ar?: string | null;
}

/**
 * These numeric fields come back as plain numbers under `en`, but as
 * Arabic-Indic digit strings (e.g. `"٢"`) under `ar` — see `toNumber()` in
 * `lib/helpers.ts`. Typed `number | string` here so a `> 0` gate on one of
 * them has to go through that helper rather than compiling by accident.
 */
export interface ProfileStatistics {
  all_time?: {
    total_hours?: number | string;
    total_opportunities?: number | string;
    total_certificates?: number | string;
    opportunities_organized?: number | string;
    /**
     * Volunteer development-opportunity counter. Number of learn-serve
     * activities the volunteer took part in as Participant OR Provider — one
     * per opportunity, not per certificate. The backend returns this as
     * `development_opportunities_count`; the `total_*` aliases support older
     * API deployments during rollout.
     */
    total_volunteer_opportunities?: number | string;
    total_learn_opportunities?: number | string;
    total_development_opportunities?: number | string;
  };
}

/**
 * `profile_data.sponsorship_profile` (organization branch) —
 * `SponsorshipProfileBadge::for()`: the linked approved sponsor's type and
 * level as master choices. Either may be null; the whole block is null when
 * no sponsor record is linked.
 */
export interface SponsorshipProfile {
  type: (LocalizedValue & { slug?: string | null }) | null;
  level: (LocalizedValue & { slug?: string | null }) | null;
}

export interface ProfileData {
  id: string | number;
  nickname?: string;
  /**
   * The public identity to show. `full_name` is deliberately `null` for
   * volunteers on this endpoint — the client asked for real names to stay
   * private — so this is the field to render, never `full_name`.
   */
  display_name?: string | null;
  full_name?: string | null;
  /** Free-text status line, e.g. "university student". */
  current_status?: string | null;
  manual_id?: string;
  profile_pic?: string | null;
  /** `ar_num()` — a digit *string* under `ar`, which is why it is widened. */
  registration_number?: string | null;
  /**
   * Organization branch only, and missing until now: `profile_data` has
   * **two shapes**, chosen by `user_type` inside
   * `WebsitePublicProfileResource`, and the organization one carries
   * `license_number` beside `registration_number`. The team profile screen
   * reads it (`fromPublicTeamProfile`), which nothing checked while that
   * module typed its input as `any`.
   *
   * `ar_num()` again, hence the string.
   */
  license_number?: string | null;
  /* `id` is an integer and `document` is `getimg($row->document)`, so null
     for a row with no file — the old `{ id: string; document: string }` was
     wrong on both counts. */
  documents?: Array<{ id: number; document: string | null }>;
  company_name?: string;
  /**
   * BE-127 — **"this entity is governmental"**, computed from its organizer
   * type. Organization branch only.
   *
   * The name is unfortunate and worth knowing about: `is_verified` already
   * means two other things in this API. On the sign-in payload it is
   * `organization_status === 'approved'`
   * (`WebsiteLoginUserResource::isVerified()`), and on a volunteer profile it
   * is the volunteer-verification flag. Three fields, one name, three
   * meanings — so never carry a value from one of them into a check meant for
   * another. We have asked for this one to be renamed.
   */
  is_verified?: boolean | null;
  /** 55e6e46 — the explicit flag; same answer as `is_verified` for an organization. */
  is_government_entity?: boolean | null;
  /** Leaderboard position in the configured period; null when unranked. */
  current_rank?: number | string | null;
  /** Organization branch only — PDF p.31 sponsorship type and level. */
  sponsorship_profile?: SponsorshipProfile | null;
  /** BE-132 — which stat tiles to show (organizations and teams too since `0572fb7`). */
  counter_visibility?: CounterVisibility | null;
  sector_display?: LocalizedValue | null;
  /** **`null`, not `[]`**, when there are none — `masterChoiceCollection()`. */
  interest_display?: LocalizedValue[] | null;
  occupation?: string;
  experience?: string;
  gender_display?: LocalizedValue;
  facebook_link?: string | null;
  twitter_link?: string | null;
  whatsapp_link?: string | null;
  instagram_link?: string | null;
  linkedin_link?: string | null;
  organization_hours?: number | string | null;
  learn_opportunity_organized?: number | string | null;
  vol_opportunity_organized?: number | string | null;
  sponsored?: number | string | null;
  /** Alias returned by `/organization-profile/` — public-profile uses `sponsored`. */
  sponsored_count?: number | string | null;
  total_volunteer_hours?: number | string;
  total_opportunities?: number | string;
  total_certificates?: number | string;
  /**
   * Volunteer split counters.
   * `development_opportunities_count` is the canonical backend field —
   * attended learn-serve registrations plus created (approved) learn-serve
   * opportunities, one per role, never certificates. `total_opportunities` is
   * the attended total across volunteer and development opportunities.
   */
  development_opportunities_count?: number | string | null;
  total_volunteer_opportunities?: number | string | null;
  total_learn_opportunities?: number | string | null;
  total_development_opportunities?: number | string | null;
  learn_opportunities_count?: number | string | null;
  opportunities_organized?: number | string;
  statistics?: ProfileStatistics;
}

/**
 * `GET /public-profile/{id}/` — `WebsitePublicProfileResource`.
 *
 * Two corrections over the previous shape:
 *
 * - **`profile_data` can be `null`.** The resource fills it in an
 *   `if (isVolunteer()) … elseif (isOrganization())` and leaves it null
 *   otherwise. `UserType` is `volunteer | organization | admin` — there is no
 *   `individual` case, despite what the repo's `CLAUDE.md` says — so an admin
 *   id produces a response with every top-level key present and no profile at
 *   all.
 * - **`user_type` includes `admin`**, for the same reason.
 *
 * `id` is the user's id and is repeated inside `profile_data.id`.
 */
export interface PublicProfileResponse {
  id: number;
  user_type: "organization" | "volunteer" | "admin" | (string & {});
  is_public?: boolean;
  is_volunteer_team?: boolean;
  badge_info?: ProfileBadgeInfo | null;
  profile_data: ProfileData | null;
}

/**
 * One row of the **mixed** list `/list-all-opportunities/` returns: a
 * volunteer card, a learn & serve card, or an event card.
 *
 * Deliberately spanning all three — which is why both `opportunity_status` and
 * `event_status` appear, and why the image list has two names. The field types
 * are the resources' own, which this interface previously understated in three
 * ways:
 *
 * - every `title_*`, `location_*`, date and time column is **nullable**, not
 *   merely optional, so `string | null` rather than `string`;
 * - `from_age`/`to_age` go through `ar_num()` on the card resources, so they
 *   are `number | string` — a *string* under an Arabic locale, which is why
 *   anything comparing them routes through `toNumber()`;
 * - `opportunity_images[].image` and `event_images[].image` are
 *   `getimg($x) : null`, so null for an empty column.
 *
 * `format` is kept because the profile filter writes it locally; no resource
 * emits it.
 */
export interface OpportunityItem {
  id: string | number;
  title_en?: string | null;
  title_ar?: string | null;
  opportunity_type?: string;
  opportunity_status?: string;
  event_status?: string;
  start_date?: string | null;
  end_date?: string | null;
  start_time?: string | null;
  end_time?: string | null;
  location_en?: string | null;
  location_ar?: string | null;
  from_age?: ArabicNumeric | null;
  to_age?: ArabicNumeric | null;
  /** Client-side filter value — not emitted by any resource. */
  format?: string | null;
  format_display?: LocalizedValue | null;
  learning_type_display?: LocalizedValue | null;
  event_type_display?: LocalizedValue | null;
  participation_type_display?: LocalizedValue | null;
  interest_display?: LocalizedValue[] | null;
  opportunity_images?: Array<{ image: string | null }> | null;
  /** Events only: the card artwork (`license_image`); `event_images` holds documentation photos. */
  cover_image?: string | null;
  event_images?: Array<{ image: string | null }> | null;
}

export interface CertificateItem {
  registration_id: number;
  certificate_image: string;
  opportunity__title_en?: string;
  opportunity__title_ar?: string;
}

/** Guards against malformed/mixed entries in the `/user-certificates/` payload. */
export function isCertificateItem(value: unknown): value is CertificateItem {
  return (
    typeof value === "object" &&
    value !== null &&
    typeof (value as CertificateItem).registration_id === "number" &&
    typeof (value as CertificateItem).certificate_image === "string" &&
    (value as CertificateItem).certificate_image.length > 0
  );
}

export type ProfileSection = "opportunities" | "events" | "certificates";
export type ListingMode = "organized" | "sponsored";
export type OpportunityTypeFilter = "all" | "volunteer" | "development";

export const OPPORTUNITY_TYPE_TABS: Array<{
  value: OpportunityTypeFilter;
  labelKey: string;
}> = [
  { value: "all", labelKey: "COMMON.ALL" },
  { value: "volunteer", labelKey: "COMMON.VOLUNTEER" },
  { value: "development", labelKey: "COMMON.LEARN_SERVE" },
];

/**
 * `/list-all-opportunities/` and `/list-user-opportunities/` accept **both**
 * vocabularies for `opportunity_type` — the short `volunteer` / `learn` and the
 * long `volunteer_opportunity` / `learn_serve_opportunity` (backend confirmed
 * 2026-09-07, BE-02/BE-15 in `docs/resolved/BACKEND_ISSUES_ROUND_1.md`; the short form was the
 * only one matched before that, which is why the long form silently returned
 * everything). The long form is used here so this screen and
 * `ProfileDescriptionTabs.tsx` send one vocabulary, and so the param matches
 * the `opportunity_type` value the same rows report back.
 *
 * Note an unrecognised value is still a silent no-op server-side, not a 422 —
 * a typo here returns an unfiltered list rather than an error.
 */
export const OPPORTUNITY_TYPE_PARAM: Record<
  Exclude<OpportunityTypeFilter, "all">,
  string
> = {
  volunteer: "volunteer_opportunity",
  development: "learn_serve_opportunity",
};

export const asset = (path: string) => `/assets/${path}`;

/** `badge_info` as the API sends it (`ResolvesApiPayloads::badgeInfoPayload`). */
export interface ProfileBadgeInfo {
  id?: number;
  name?: string | null;
  /** bronze / silver / gold / distinguished_gold; null on pre-tier rows. */
  tier?: string | null;
  image?: string | null;
}

/** The label key of a badge: by `tier`, else the old English name. */
export function badgeLabelKey(badge?: ProfileBadgeInfo | null) {
  switch (badge?.tier ?? badge?.name) {
    case "gold":
    case "Gold Badge":
      return "COMMON.GOLD_BADGE";
    case "silver":
    case "Silver Badge":
      return "COMMON.SILVER_BADGE";
    case "distinguished_gold":
    case "Super Gold Badge":
      return "COMMON.SUPER_GOLD_BADGE";
    case "bronze":
    case "Bronze Badge":
      return "COMMON.BRONZE_BADGE";
    default:
      return undefined;
  }
}

/** Bundled badge artwork by tier; backend-uploaded images are intentionally ignored. */
export function badgeImage(
  badge?: { name?: string | null; tier?: string | null; image?: string | null } | null
) {
  switch (badge?.tier ?? badge?.name) {
    case "gold":
    case "Gold Badge":
      return asset("profile/badge.svg");
    case "silver":
    case "Silver Badge":
      return asset("profile/silver_badge.svg");
    case "distinguished_gold":
    case "Super Gold Badge":
      return asset("profile/super_gold_badge.svg");
    case "bronze":
    case "Bronze Badge":
      return asset("profile/bronze_badge.svg");
    default:
      return null;
  }
}

export function localizedError(error: unknown, language: string, fallback: string) {
  const payload = (
    error as {
      response?: { data?: { msg?: string; message_en?: string; message_ar?: string } };
    }
  )?.response?.data;
  return payload?.msg || (language === "ar" ? payload?.message_ar : payload?.message_en) || fallback;
}
