import moment from "moment";
import { getOpportunityButtonState, isUnpaidCheckoutAttempt } from "@/features/shared/opportunityButtonState";
import { hasOpportunityEnded, hasOpportunityStarted, opportunityStartsAt, opportunityEndsAt, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";
import type {
  OwnerAttendanceStatus,
  ProfileActivityTag,
  RelationshipTag,
} from "@/features/opportunities/opportunityRecord";

/**
 * The pills on an opportunity card's cover (client's design, 2026-10-10):
 *
 *  - **price** — development only: the price («33 د.ك») or «مجاني» (dark);
 *  - **relation** — «مقدم» / «منظم» (organizer), «راعي» (sponsor), «مشارك»
 *    (started) or «تم التسجيل» (before it starts) in teal; once it is over and
 *    the person was registered, «حضرت» / «لم تحضر» (dark) instead.
 *
 * Whose relation depends on where the card is:
 *
 *  - `viewer` — every list: the signed-in user's own `relationship_tags`;
 *  - `profile-individual` — a person's profile: the **profile owner's**
 *    `profile_activity_tag` + `owner_attendance_status`, never the viewer's
 *    tags, which would label someone else's history with your own;
 *  - `profile-organizer` — an organization's own listings: it organized all
 *    of them.
 *
 * Plus the **state** pill (client, 2026-10-14) — «انتهت», «بدأت», «امتلأت» or
 * «مغلق». Since 2026-10-18 the action button shows the state again, so
 * `OpportunityCardCover` drops this pill when the button already says it; it
 * remains for viewers whose button reads «التفاصيل» (the creator, an
 * organization).
 */
export type CardBadgePerspective =
  | "viewer"
  | "profile-individual"
  /** Someone else's individual profile: «حضرت» / «لم تحضر» are hidden — the
      client's rule is that only the profile's owner sees attendance. */
  | "profile-individual-public"
  | "profile-organizer"
  /** An organization's «راعي» list — everything in it is sponsored. */
  | "profile-sponsor";

export interface CardBadgeSource extends ReviewSchedule {
  opportunity_type?: string | null;
  opportunity_status?: string | null;
  has_ended?: boolean | null;
  has_started?: boolean | null;
  is_paid?: boolean | null;
  /** KWD; on the development card payload next to `is_paid`. */
  price?: number | string | null;
  relationship_tags?: RelationshipTag[] | null;
  profile_activity_tag?: ProfileActivityTag | string | null;
  owner_attendance_status?: OwnerAttendanceStatus | null;
  /* What the state pill reads — the same inputs the old action button used. */
  action_state?: string | null;
  is_registered?: boolean | null;
  /** Development card: the viewer's payment and cancellation state. */
  payment_status?: string | null;
  cancellation_status?: string | null;
  is_registration_open?: boolean | null;
  is_registration_closed?: boolean | null;
  registered_volunteers_count?: number | string | null;
  participants_needed?: number | string | null;
}

/** «انتهت» / «بدأت» / «امتلأت» / «مغلق», or nothing while it is open to join. */
function stateBadgeKey(item: CardBadgeSource, now: moment.Moment): string | null {
  if (item.opportunity_status === "cancelled") return "COMMON.CANCELLED";
  if (isOver(item, now)) return "COMMON.ENDED";
  if (isStarted(item, now)) {
    return "COMMON.STARTED";
  }
  const state = getOpportunityButtonState(item, now);
  if (state === "full") return "COMMON.FULL";
  if (state === "closed") return "COMMON.CLOSED";
  return null;
}

export interface CardBadge {
  /** i18n key. */
  label: string;
  /** Literal text shown instead of `t(label)` — the price, e.g. "33 KWD". */
  text?: string;
  tone: CardTagKind;
}

/**
 * What a tag means, which decides its colour (client's colour key,
 * 2026-10-14): provider / organizer navy, sponsor orange, free solid blue,
 * paid / a price outlined in blue, attended lime, absent grey. `participant`
 * («مشارك») and `state` («انتهت», «بدأت», «مغلق», «امتلأت») are not in the key
 * and keep colours of their own that clash with none of it.
 */
export type CardTagKind =
  | "provider"
  | "sponsor"
  | "free"
  | "paid"
  | "attended"
  | "absent"
  | "participant"
  | "state";

/** Literal class names — Tailwind only extracts whole strings. Shared by the
    opportunity cover and the event cover so the two families cannot drift. */
export const CARD_TAG_CLASS: Record<CardTagKind, string> = {
  provider: "bg-primary-5 text-white",
  sponsor: "bg-primary-801 text-white",
  free: "bg-primary-501 text-white font-bold",
  paid: "border border-primary-501 bg-white text-primary-501 font-bold",
  attended: "bg-primary-505 text-primary-5",
  absent: "bg-[#E4E4E0] text-secondary-101",
  participant: "bg-primary-503 text-white",
  state: "bg-secondary-101 text-white",
};

type Relation = "organizer" | "sponsor" | "registered" | "participant" | "attended" | "absent" | null;

const hasSchedule = (item: CardBadgeSource) => Boolean(opportunityStartsAt(item) || opportunityEndsAt(item));
const isOver = (item: CardBadgeSource, now: moment.Moment) => hasSchedule(item) ? hasOpportunityEnded(item, now)
  : item.has_ended === true || item.opportunity_status === "completed" || item.action_state === "ended";
const isStarted = (item: CardBadgeSource, now: moment.Moment) => hasSchedule(item) ? hasOpportunityStarted(item, now)
  : item.has_started === true || item.opportunity_status === "inprogress" || item.action_state === "started";

const registrationRelation = (item: CardBadgeSource, now: moment.Moment): Relation =>
  item.opportunity_status === "cancelled" || isOver(item, now)
    ? null // Only the server's finalized attendance outcome may label a no-show.
    : isStarted(item, now)
      ? "participant"
      : "registered";

function viewerRelation(item: CardBadgeSource, now: moment.Moment): Relation {
  const tags = item.relationship_tags ?? [];
  if (tags.includes("organizer")) return "organizer";
  if (tags.includes("sponsor")) return "sponsor";
  if (tags.includes("attended")) return "attended";
  if (tags.includes("registered") || item.is_registered) {
    // Refunded, cancelled or never-paid bookings hold no seat; the card still tags them.
    const noSeat = item.payment_status === "refunded" || item.cancellation_status === "approved" || isUnpaidCheckoutAttempt(item);
    return noSeat ? null : registrationRelation(item, now);
  }
  return null;
}

/*
 * The server's `owner_attendance_status` wins (BE-97 C). The tag-based
 * fallback covers the public profile, which does not send it — there a
 * no-show arrives as no tag at all, so nothing is claimed. `participant` is
 * the backend's word for an *attended* development registration.
 */
function profileRelation(item: CardBadgeSource, now: moment.Moment): Relation {
  const tag = item.profile_activity_tag;
  if (tag === "provider") return "organizer";
  if (item.owner_attendance_status === "attended") return "attended";
  if (item.owner_attendance_status === "absent") return "absent";
  if (item.owner_attendance_status === "upcoming") return registrationRelation(item, now);
  if (tag === "attended" || tag === "participant") return "attended";
  if (tag === "registered") return registrationRelation(item, now);
  return null;
}

function creatorIsIndividual(
  perspective: CardBadgePerspective,
  viewerIsIndividual: boolean | undefined,
  isLearnServe: boolean
): boolean {
  if (perspective === "profile-organizer" || perspective === "profile-sponsor") return false;
  if (perspective !== "viewer") return true;
  // Unknown viewer: the old reading — only individuals give courses.
  return viewerIsIndividual ?? isLearnServe;
}

export function cardStatusBadges(
  item: CardBadgeSource,
  perspective: CardBadgePerspective,
  isLearnServe: boolean,
  /**
   * Whether the viewer's own account is an individual — only read for the
   * `viewer` perspective, where «منظم / مقدم» means "you created this". The
   * card payload carries just the creator's id, so the account type comes
   * from whoever the badge is about: the viewer here, the profile owner on a
   * profile.
   */
  viewerIsIndividual?: boolean,
  now: moment.Moment = moment(),
): CardBadge[] {
  const badges: CardBadge[] = [];

  const relation =
    perspective === "profile-organizer"
      ? "organizer"
      : perspective === "profile-sponsor"
        ? "sponsor"
        : perspective === "profile-individual" || perspective === "profile-individual-public"
        ? profileRelation(item, now)
        : viewerRelation(item, now);

  // The order of the client's key: who you are to it, then the price, then
  // attendance — and the opportunity's state last.
  switch (relation) {
    case "organizer":
      badges.push({
        // By who created it (client, 2026-10-18): an individual is «مقدم»,
        // an organization or a volunteer team «منظم» — on either kind.
        label: creatorIsIndividual(perspective, viewerIsIndividual, isLearnServe)
          ? "COMMON.PROFILE_BADGE_PROVIDER"
          : "COMMON.CARD_BADGE_ORGANIZER",
        tone: "provider",
      });
      break;
    case "sponsor":
      badges.push({ label: "COMMON.CARD_BADGE_SPONSOR", tone: "sponsor" });
      break;
    case "registered":
      badges.push({ label: "COMMON.CARD_REGISTERED_PAID", tone: "participant" });
      break;
    case "participant":
      // Individual profiles omit the participant pill on development cards.
      if (!(isLearnServe && (perspective === "profile-individual" || perspective === "profile-individual-public"))) {
        badges.push({ label: "COMMON.PROFILE_BADGE_PARTICIPANT", tone: "participant" });
      }
      break;
  }

  if (isLearnServe) {
    badges.push({
      label: item.is_paid ? "COMMON.PROFILE_BADGE_PAID" : "COMMON.PROFILE_BADGE_FREE",
      tone: item.is_paid ? "paid" : "free",
      // A paid one shows its price (client, 2026-10-14) — «مدفوعة» only when
      // the payload carries no amount. The text is formatted by the cover,
      // which has `t`; this marks it.
      ...(item.is_paid && item.price != null ? { text: String(item.price) } : {}),
    });
  }

  // Attendance is the profile owner's own business: hidden on someone else's
  // individual profile.
  if (perspective === "profile-individual") {
    if (relation === "attended") {
      badges.push({ label: "COMMON.PROFILE_BADGE_ATTENDED", tone: "attended" });
    } else if (relation === "absent") {
      badges.push({ label: "COMMON.PROFILE_BADGE_ABSENT", tone: "absent" });
    }
  }

  const stateKey = stateBadgeKey(item, now);
  const hideLifecycleBadge =
    (perspective === "profile-organizer" || perspective === "profile-sponsor") &&
    (stateKey === "COMMON.STARTED" || stateKey === "COMMON.ENDED");
  if (stateKey && !hideLifecycleBadge) badges.push({ label: stateKey, tone: "state" });

  return badges;
}
