/**
 * The registration list's selection rules.
 *
 * Attendance is marked in bulk, so the list keeps three pieces of state that
 * have to agree: which rows are ticked, whether the header box is ticked, and
 * whether "select all" is still *in force* for pages that have not loaded yet.
 * That third one is the subtle part — with an infinitely scrolling list, "all"
 * has to keep applying to rows the organizer has not seen.
 *
 * Pure, because every one of those rules is a decision with an edge case and
 * none of them needs React to be checked.
 */

/** The fields the rules read off a row. */
export interface SelectableRegistration {
  id: number | string;
  /** Nullable on `LearnServeOpportunityRegistrationResource`; falsy means "not attended". */
  is_attended?: boolean | null;
}

export interface SelectionState {
  selectedUsers: string[];
  /** The header checkbox. */
  selectAll: boolean;
  /** Still in force, so newly loaded rows get ticked too. */
  selectAllMode: boolean;
}

/** Only rows not already marked present can be selected. */
export const selectableIds = (rows: SelectableRegistration[]): string[] =>
  rows.filter((row) => !row.is_attended).map((row) => row.id.toString());

/**
 * Toggling the header checkbox.
 *
 * Selects from **every loaded row**, not just the visible page — the organizer
 * who ticks "all" after scrolling means all of them.
 */
export function toggleSelectAll(
  rows: SelectableRegistration[],
  current: SelectionState
): SelectionState {
  const selectAll = !current.selectAll;
  return {
    selectAll,
    selectAllMode: selectAll,
    selectedUsers: selectAll ? selectableIds(rows) : [],
  };
}

/**
 * Toggling one row.
 *
 * Unticking a row **cancels select-all mode**: the organizer has just said "not
 * that one", so rows loaded afterwards must not be ticked on their behalf.
 * Ticking one does not restore it — only the header box does.
 *
 * The header box then re-derives from whether every selectable row is now
 * selected, so ticking the last one by hand still lights it up.
 */
export function toggleRegistration(
  userId: string | number,
  rows: SelectableRegistration[],
  current: SelectionState
): SelectionState {
  const userIdStr = userId.toString();
  const wasSelected = current.selectedUsers.includes(userIdStr);

  const selectedUsers = wasSelected
    ? current.selectedUsers.filter((id) => id !== userIdStr)
    : [...current.selectedUsers, userIdStr];

  const selectable = rows.filter((row) => !row.is_attended);
  const allSelected =
    selectable.length > 0 &&
    selectable.every(
      (row) => selectedUsers.includes(row.id.toString()) || row.is_attended
    );

  return {
    selectedUsers,
    selectAll: allSelected,
    // Cancelled by an untick, otherwise carried through unchanged.
    selectAllMode: wasSelected ? false : current.selectAllMode,
  };
}

/**
 * The ids to add when a further page arrives while select-all is in force.
 * Already-selected ids are filtered out so the list cannot gain duplicates.
 */
export function idsToAutoSelect(
  newRows: SelectableRegistration[],
  selectedUsers: string[]
): string[] {
  return selectableIds(newRows).filter((id) => !selectedUsers.includes(id));
}

/** Nothing selected, nothing in force — after a search, a delete or a save. */
export const EMPTY_SELECTION: SelectionState = {
  selectedUsers: [],
  selectAll: false,
  selectAllMode: false,
};

/**
 * The selection as it actually applies to the rows currently loaded.
 *
 * While `selectAllMode` is in force the answer is **derived** — every
 * selectable row among those loaded — rather than accumulated page by page.
 * That is sound because the only way to keep the mode on is never to untick
 * anything: `toggleRegistration` clears it on an untick, and `toggleSelectAll`
 * is the only thing that sets it.
 *
 * Deriving replaces an `onPageMerged(newRows)` callback that the paging hook
 * invoked for each merged page, reached through a ref so it would not be a
 * render-time write. The callback could also disagree with the header toggle
 * about which rows were eligible — they computed eligibility from different
 * arguments — and one expression cannot disagree with itself.
 */
export function effectiveSelectedUsers(
  state: SelectionState,
  rows: SelectableRegistration[]
): string[] {
  return state.selectAllMode ? selectableIds(rows) : state.selectedUsers;
}
