/** Registration and creator actions under the approved 25 October client rules. */
import moment from "moment";
import { hasOpportunityStarted, hasOpportunityEnded, isOpportunityCancelled, isBeforeCancellationCutoff, opportunityStartsAt, parseKuwaitInstant, type ReviewSchedule } from "./clientReviewPolicy";
import { toNumber } from "@/lib/helpers";

export type OpportunityButtonState =
  | "ended"
  | "started"
  | "full"
  | "closed"
  | "unregister"
  | "register"
  | "unavailable"
  | "registered"
  | "booked"
  | "cancelled"
  | "cancellation_pending";

/**
 * A participant's cancellation request that is still open. Backend `bf3140b`
 * splits the old `pending` into `awaiting_trainer`, `pending`, `refunding` and
 * `refund_failed`; the participant sees «طلب الإلغاء قيد المراجعة» for all of
 * them (PDF p.18) until the refund is confirmed.
 */
const OPEN_CANCELLATION_STATES: ReadonlySet<string> = new Set(["awaiting_trainer", "pending", "refunding", "refund_failed"]);

export function isCancellationRequestOpen(status: string | null | undefined): boolean {
  return OPEN_CANCELLATION_STATES.has(status ?? "");
}

const OPPORTUNITY_BUTTON_STATES: ReadonlySet<string> = new Set([
  "ended",
  "started",
  "full",
  "closed",
  "unregister",
  "register",
]);

export interface OpportunityButtonSource extends ReviewSchedule {
  opportunity_type?: string | null;
  is_paid?: boolean | null;
  payment_status?: string | null;
  cancellation_status?: string | null;
  registration_closes_at?: string | null;
  action_state?: string | null;
  opportunity_status?: string | null;
  is_registered?: boolean | null;
  is_registration_open?: boolean | null;
  /** True only after an explicit organizer reopen, never the initial open flag. */
  can_register_while_running?: boolean | null;
  is_registration_closed?: boolean | null;
  /** The API sends these as Arabic-Indic digit strings under `ar` — run through `toNumber()`. */
  registered_volunteers_count?: number | string | null;
  participants_needed?: number | string | null;
}

/** i18n key each state renders with. */
const STATE_LABEL_KEYS: Record<OpportunityButtonState, string> = {
  ended: "COMMON.ENDED",
  started: "COMMON.STARTED",
  full: "COMMON.FULL",
  closed: "COMMON.CLOSED",
  unregister: "COMMON.UNREGISTER",
  register: "COMMON.REGISTER",
  unavailable: "COMMON.REGISTRATION_UNAVAILABLE",
  registered: "COMMON.REGISTERED",
  booked: "COMMON.BOOKED",
  cancelled: "COMMON.CANCELLED",
  cancellation_pending: "COMMON.CANCELLATION_PENDING",
};

/** Only `unregister` and `register` are actions; the rest are read-only states. */
const ACTIONABLE_STATES: ReadonlySet<OpportunityButtonState> = new Set<
  OpportunityButtonState
>(["unregister", "register"]);

const UNPAID_PAYMENT_STATES: ReadonlySet<string> = new Set(["pending", "failed", "canceled", "cancelled", "expired"]);

/**
 * A paid development booking whose payment never completed holds no seat
 * (BE-231). Backend `b6ed21c` reports that seat-based on every payload — card,
 * detail, `action_state`, `relationship_tags` and `/home/` — so this is now a
 * guard for an API that predates it (staging still does), not a correction.
 */
export function isUnpaidCheckoutAttempt(
  item: Pick<OpportunityButtonSource, "opportunity_type" | "is_paid" | "payment_status">,
): boolean {
  const development = item.opportunity_type === "learn_serve_opportunity" || (!item.opportunity_type && typeof item.is_paid === "boolean");
  return development && item.is_paid === true && UNPAID_PAYMENT_STATES.has(item.payment_status ?? "");
}

export function getOpportunityButtonState(
  item: OpportunityButtonSource | null | undefined,
  now: moment.Moment = moment(),
): OpportunityButtonState {
  if (!item) return "register";
  const development = item.opportunity_type === "learn_serve_opportunity" || (!item.opportunity_type && typeof item.is_paid === "boolean");
  if (isOpportunityCancelled(item) || item.payment_status === "refunded" || item.cancellation_status === "approved") return "cancelled";
  if (isCancellationRequestOpen(item.cancellation_status)) return "cancellation_pending";
  if (hasOpportunityEnded(item, now)) return "ended";
  if (item.is_registered && !isUnpaidCheckoutAttempt(item)) {
    if (hasOpportunityStarted(item, now)) return "started";
    if (development && item.is_paid) return "booked";
    return isBeforeCancellationCutoff(item, now) ? "unregister" : "registered";
  }
  const started = hasOpportunityStarted(item, now);
  // Volunteering can reopen during execution; development never does.
  if (started && (development || item.can_register_while_running !== true || item.is_registration_open === false || item.is_registration_closed === true)) return "started";
  // The organizer's close wins over capacity, as in the server's `HasActionState::actionState()` (PDF p.13: «مغلق»).
  const registrationClosesAt = parseKuwaitInstant(item.registration_closes_at);
  if (item.is_registration_closed === true || item.is_registration_open === false || Boolean(registrationClosesAt && now.isSameOrAfter(registrationClosesAt))) return development ? "unavailable" : "closed";
  const registered = toNumber(item.registered_volunteers_count);
  const needed = toNumber(item.participants_needed);
  if (needed > 0 && registered >= needed) return "full";
  if (!opportunityStartsAt(item) && item.action_state && OPPORTUNITY_BUTTON_STATES.has(item.action_state)) return item.action_state as OpportunityButtonState;
  return "register";
}

export function getOpportunityButtonLabelKey(
  state: OpportunityButtonState
): string {
  return STATE_LABEL_KEYS[state];
}

export interface CreatorRepostSource extends ReviewSchedule {
  action_state?: string | null;
  opportunity_status?: string | null;
  start_date?: string | null;
}

/** Reposting creates a new record and is available from the actual start. */
export function isCreatorRepostState(
  item: CreatorRepostSource | null | undefined, now: moment.Moment = moment()
): boolean {
  if (!item) return false;
  return hasOpportunityStarted(item, now) || hasOpportunityEnded(item, now);

}

export interface EditWindowSource extends ReviewSchedule {
  start_date?: string | null;
}

export function canEditOrDelete(
  item: EditWindowSource | null | undefined, now: moment.Moment = moment()
): boolean {
  return isBeforeCancellationCutoff(item, now);

}

/** True when pressing the button does something (register / unregister). */
export function isOpportunityButtonActionable(
  state: OpportunityButtonState
): boolean {
  return ACTIONABLE_STATES.has(state);
}

/** The subset of a payload the "is the viewer this opportunity's organizer?" check reads. */
export interface OrganizerSource {
  /** `organizer` / `sponsor` / `registered` / `attended`, computed per requesting user. */
  relationship_tags?: string[] | null;
  /** Legacy flag — missing on newer detail payloads, false/absent on some older ones. */
  is_creator?: boolean | null;
  created_by?: { id?: number | string | null } | null;
}

/**
 * Whether the current viewer owns this opportunity.
 *
 * Three signals, ORed, because none of them is reliable on its own:
 *   1. `relationship_tags` contains `"organizer"` — the current, per-user field.
 *      `GET /opportunities/{id}/details/` no longer sends `is_creator` at all,
 *      so this is the only positive signal on that response.
 *   2. `is_creator` — still sent by the list endpoints; false/missing on some
 *      records that really are the viewer's (see opportunity #121).
 *   3. `created_by.id === user.id` — what the cards have always compared, and
 *      the only fallback for payloads carrying neither field.
 */
export function isViewerOrganizer(
  item: OrganizerSource | null | undefined,
  userId?: number | string | null
): boolean {
  if (!item) return false;
  if (item.relationship_tags?.includes("organizer")) return true;
  if (item.is_creator) return true;
  return (
    Boolean(userId) && String(item.created_by?.id ?? "") === String(userId)
  );
}

export interface RegistrationToggleSource extends ReviewSchedule {
  end_date?: string | null;
  due_date?: string | null;
}

/** Volunteering registration can be reopened until its actual end. */
export function canToggleRegistration(
  item: RegistrationToggleSource | null | undefined, now: moment.Moment = moment()
): boolean {
  return Boolean(item) && !isOpportunityCancelled(item) && !hasOpportunityEnded(item, now);

}
