import moment from "moment";
import { opportunityStartsAt, opportunityEndsAt, parseKuwaitInstant, isOpportunityCancelled, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";

export interface CheckInWindowSource extends ReviewSchedule {
  start_date?: string | null;
  end_date?: string | null;
  preparation_valid_until?: string | null;
  preparation_valid_until_at?: string | null;
  is_preparation_window_closed?: boolean | null;
  preparation_reopened_until?: string | null;
  requires_check_in?: boolean | null;
  qr_attendance_enabled?: boolean | null;
  manual_attendance_enabled?: boolean | null;
  manual_tracking?: boolean | null;
}

export interface CheckInWindow {
  /** End of the window, or null when nothing in the payload pins it down. */
  endsAt: moment.Moment | null;
  /** True once the window has shut — the backend's flag wins when it is sent. */
  isClosed: boolean;
  /** True while attendance may actually be recorded. */
  isOpen: boolean;
  /** An admin extended this window past its original deadline. */
  wasReopened: boolean;
  /** Actual attendance is required for all reviewed development types. */
  requiresCheckIn: boolean;
  /** QR scanning is offered for this opportunity. */
  qrEnabled: boolean;
  /** Marking someone present by hand is offered for this opportunity. */
  manualEnabled: boolean;
  /**
   * How many days the window runs for, measured from the end of the
   * opportunity's last day to `endsAt` — i.e. the configured length, derived
   * from the two dates the payload already carries rather than restated as a
   * constant. Null when either date is missing, or when an admin reopened the
   * window (the extension is not the configured length).
   *
   * It exists because the countdown alone misleads: an organizer looking at a
   * still-running opportunity sees "2 months left" and reads that as the
   * window being two months long. It is not — it is today-to-deadline.
   */
  windowDays: number | null;
}

/** Legacy fallback matching the backend's current default of 72 hours. */
const FALLBACK_WINDOW_HOURS = 72;

export function getCheckInWindow(
  item: CheckInWindowSource | null | undefined,
  now: moment.Moment = moment()
): CheckInWindow {
  // Legacy type-specific opt-outs no longer grant automatic attendance.
  const requiresCheckIn = true;

  if (!item) {
    return {
      endsAt: null,
      isClosed: false,
      isOpen: false,
      wasReopened: false,
      requiresCheckIn,
      qrEnabled: false,
      manualEnabled: false,
      windowDays: null,
    };
  }

  const reopenedUntil = parseKuwaitInstant(item.preparation_reopened_until);
  const wasReopened = reopenedUntil !== null;
  const effectiveUntil = parseKuwaitInstant(item.preparation_valid_until_at);
  const legacyUntil = parseKuwaitInstant(item.preparation_valid_until);
  if (legacyUntil && item.preparation_valid_until?.length === 10) legacyUntil.endOf("day");
  const naturalUntil = opportunityEndsAt(item)?.clone().add(FALLBACK_WINDOW_HOURS, "hours") ?? null;
  const endsAt = reopenedUntil && effectiveUntil ? moment.max(reopenedUntil, effectiveUntil)
    : reopenedUntil ?? effectiveUntil ?? legacyUntil ?? naturalUntil;

  // A reopened window overrides a stale `is_preparation_window_closed: true`.
  const closedByBackend =
    !wasReopened && item.is_preparation_window_closed === true;
  const isClosed =
    isOpportunityCancelled(item) || closedByBackend || (endsAt ? now.isSameOrAfter(endsAt) : false);

  // Attendance cannot be taken before the opportunity itself starts.
  const startsAt = opportunityStartsAt(item);
  const hasStarted = startsAt ? now.isSameOrAfter(startsAt) : false;

  const isOpen = requiresCheckIn && hasStarted && !isClosed;

  // Describe the configured correction period relative to the actual session end.
  const windowDays =
    !wasReopened && endsAt && item.end_date && moment(item.end_date).isValid()
      ? Math.round(
          moment
            .duration(endsAt.diff(opportunityEndsAt(item) ?? moment(item.end_date)))
            .asDays()
        )
      : null;

  return {
    endsAt,
    isClosed,
    isOpen,
    wasReopened,
    requiresCheckIn,
    // QR respects the server flag; manual correction is the required fallback.
    qrEnabled: requiresCheckIn && item.qr_attendance_enabled !== false,
    manualEnabled: requiresCheckIn,
    windowDays: windowDays !== null && windowDays > 0 ? windowDays : null,
  };
}

/**
 * Human-readable time left in the window, e.g. "2 days" / "5 hours". Returns
 * null once the window has closed or when there is no deadline to count to.
 */
export function getCheckInCountdown(
  window: CheckInWindow,
  now: moment.Moment = moment(),
  language = "en",
): string | null {
  if (!window.endsAt || window.isClosed) return null;
  return moment.duration(window.endsAt.diff(now)).locale(language).humanize();
}


/** Clone before localizing: cached window objects can outlive a language switch. */
export function formatCheckInDeadline(window: CheckInWindow, language: string): string | null {
  return window.endsAt?.clone().utcOffset(180).locale(language).format("DD MMM YYYY, hh:mm A") ?? null;
}
