import moment from "moment";
import { hasOpportunityEnded, isOpportunityCancelled } from "@/features/shared/clientReviewPolicy";
import { sanitizeRichText } from "@/lib/sanitizeRichText";
import { getOpportunityButtonState, getOpportunityButtonLabelKey, isOpportunityButtonActionable, canEditOrDelete, isCreatorRepostState, isCancellationRequestOpen } from "@/features/shared/opportunityButtonState";
import { type LearnServeOpportunityData } from "./learnServeDetailsTypes";

/** Only the viewer fields the rules below read. */
export interface LearnServeViewer {
  id?: string | number;
  is_verified?: boolean | null;
  user_type?: string | null;
  auth_token?: string | null;
}

interface ViewStateInput {
  opportunityData: LearnServeOpportunityData | undefined;
  /** Already ORed from `is_creator`, the id match and `relationship_tags`. */
  isCreator: boolean;
  user: LearnServeViewer | null | undefined;
  /** Translator, passed in so this module stays free of React. */
  t: (key: string) => string;
  now?: moment.Moment;
}

/**
 * Every rule the detail page switches on, derived in one place.
 *
 * Split out of the page because these are decisions, not markup: who may close
 * registration, whether the primary action reposts or edits, which title and
 * description the current primary language selects. Keeping them in a pure
 * function means they can be asserted directly — the page cannot be.
 *
 * `t` is a parameter rather than a hook call for the same reason.
 */
export function computeLearnServeViewState({
  opportunityData,
  isCreator,
  user,
  t, now = moment(),
}: ViewStateInput) {
  const isRepostState = isCreator && isCreatorRepostState(opportunityData, now);
  const state = getOpportunityButtonState({ ...opportunityData, opportunity_type: "learn_serve_opportunity" }, now);
  const closedByCreator = state === "unavailable";
  const withinRegistrationWindow = state === "register" || state === "unregister";
  const showActionButton = isCreator || user?.user_type !== "organization";
  // Printing is preparation, independent of the participant's scan activation.
  const canIssueAttendanceCode = isCreator && Boolean(opportunityData?.id);
  const canRequestDeletion = isCreator;
  // Server capabilities first (cancelled course, pending deletion request, ever-paid price lock); the
  // client cutoff only answers for an API that predates them.
  const canEdit = canEditOrDelete(opportunityData, now) && opportunityData?.can_edit !== false;
  const canDelete = canEdit && opportunityData?.can_delete !== false && opportunityData?.has_successful_payments !== true && opportunityData?.has_active_payments !== true;
  const opportunityTitle = opportunityData?.title_ar || opportunityData?.title_en || "";
  const isPaidBooking = !isCreator && !isOpportunityButtonActionable(state);
  const actionButtonLabel = isRepostState ? t("COMMON.REPOST") : isCreator ? t("COMMON.EDIT_TEXT") : state === "register" && opportunityData?.is_paid ? t("COMMON.BOOK") : t(getOpportunityButtonLabelKey(state));
  // Server `can_message` first: true after a retained administration cancellation (PDF p.40).
  const canMessage = isCreator && (opportunityData?.can_message ?? (!isOpportunityCancelled(opportunityData) && !hasOpportunityEnded(opportunityData, now)));
  const cancellationRequest = participantCancellationRequest(opportunityData, isCreator, now);
  const organizerPath = `/public-profile/${opportunityData?.created_by?.id}`;

  // The description is always shown in full — the View More toggle was removed.
  // Rendered as HTML, so it is sanitized first: the backend stores the editor's
  // markup verbatim and any organization account can author it.
  const description = sanitizeRichText(
    opportunityData?.primary_language === "ar"
      ? opportunityData?.description_ar
      : opportunityData?.description_en
  );

  const format = opportunityData?.format_display?.value_en;
  const isInPerson = format === "IN PERSON";

  return {
    isRepostState,
    canMessage,
    cancellationRequest,
    canEdit,
    closedByCreator,
    withinRegistrationWindow,
    showActionButton,
    canIssueAttendanceCode,
    canRequestDeletion,
    canDelete,
    opportunityTitle,
    actionButtonLabel,
    isPaidBooking,
    organizerPath,
    description,
    isInPerson,
    opportunityDetails: {
      title_ar: opportunityData?.title_ar,
      title_en: opportunityData?.title_en,
      start_date: opportunityData?.start_date,
      isInPerson,
      /* BE-125 — the confirmation has to say what it is about to charge. */
      isPaid: opportunityData?.is_paid === true,
      price: opportunityData?.price ?? null,
      // Never `link`: on development that is the gated meeting URL.
      whatsapp_link: opportunityData?.whatsapp_link ?? null,
    },
  };
}

/**
 * The participant's «طلب إلغاء» button: `"available"`, `"pending"` (shown
 * disabled) or `"hidden"`.
 *
 * `cancellation_status` is the server's own answer (`CancellationRequestService::
 * statusFor`): null unless the booking is actually paid, so a pending, failed or
 * expired checkout — still `is_registered` — gets no button. The server also
 * refuses a request after the end (422), so an ended course hides it too. A
 * payload without the field (older API) falls back to `payment_status`.
 */
export function participantCancellationRequest(
  data: Pick<LearnServeOpportunityData, "is_paid" | "is_registered" | "payment_status" | "cancellation_status" | "start_at" | "end_at" | "start_date" | "end_date" | "start_time" | "end_time" | "opportunity_status" | "time_slots" | "timeslots_display"> | undefined,
  isCreator: boolean,
  now: moment.Moment = moment()
): "available" | "pending" | "hidden" {
  if (!data || isCreator || data.is_paid !== true || data.is_registered !== true) return "hidden";
  if (isOpportunityCancelled(data) || hasOpportunityEnded(data, now)) return "hidden";
  const status = data.cancellation_status;
  if (status === undefined) return data.payment_status === "paid" ? "available" : "hidden";
  if (isCancellationRequestOpen(status)) return "pending";
  return status === "available" || status === "rejected" ? "available" : "hidden";
}

/**
 * The owner's rejection notice (same block as volunteering): shown only to the
 * creator of a rejected course, with the admin's reason when the server sends it.
 */
export function learnServeRejection(
  data: Pick<LearnServeOpportunityData, "approval_status" | "rejected_reason"> | undefined,
  isCreator: boolean
): { reason: string | null } | null {
  if (!isCreator || data?.approval_status !== "rejected") return null;
  return { reason: data.rejected_reason?.trim() || null };
}

/** A deletion request already with administration (server `deletion_status`). */
export function isLearnServeDeletionPending(data: Pick<LearnServeOpportunityData, "deletion_status"> | undefined): boolean {
  return data?.deletion_status === "pending";
}

export type LearnServeViewState = ReturnType<typeof computeLearnServeViewState>;
