/**
 * Page-at-a-time list accumulation, without an effect.
 *
 * Ten hooks held three pieces of mirror state — the accumulated rows, a page
 * number and a `hasMore` flag — and kept them in step from two effects: one that
 * cleared everything when the filters changed, and one that appended whatever
 * the latest response held. That is the single largest source of
 * `react-hooks/set-state-in-effect` in the app, and the rule is pointing at a
 * real cost rather than a style preference: both effects run *after* paint, so
 * every filter change rendered one frame of the previous filter's rows before
 * clearing them, and every "load more" rendered one frame of the old list after
 * the new page had already arrived.
 *
 * The replacement is React's documented "adjusting state when a prop changes"
 * pattern — compare against the last value you acted on, and if it differs, set
 * during render. React discards the in-progress render and re-runs with the new
 * state before anything is painted, so the stale frame disappears and the
 * accumulation becomes part of the render rather than a reaction to it.
 *
 * The decisions that pagination actually requires are pure functions, tested in
 * `tests/pagedList.test.ts`:
 *
 *  - which page a response belongs to, which must come from the response and
 *    not from the current page state — those disagree while a fetch is in
 *    flight, and acting on the page state is how a page gets merged twice;
 *  - whether another page exists, which has two different answers depending on
 *    whether the endpoint sent pagination metadata at all.
 */

import { useCallback, useState } from "react";
import type { ApiPagination, ApiResponse } from "@/lib/api/types";

/**
 * The page a response describes.
 *
 * `ApiResponse::paginated()` emits exactly `page`, `limit`, `total` and
 * `total_pages` — there is **no `current_page`**, though three hooks read one as
 * a fallback. The fallback is kept here because it costs nothing and an admin
 * endpoint returning Laravel's own paginator shape would supply it; what is not
 * kept is reading the caller's page state, which lies during a fetch.
 */
export function responsePage(
  pagination: ApiPagination | undefined,
  fallback: number
): number {
  const legacy = (pagination as { current_page?: number } | undefined)
    ?.current_page;
  return pagination?.page ?? legacy ?? fallback;
}

/**
 * Whether a further page exists.
 *
 * With metadata, compare the page against `total_pages`. Without it — several
 * endpoints answer a list without a `meta` block — a full page is the only
 * available signal that there may be another, which costs one empty request at
 * the end of an exactly-divisible list and is what every call site already did.
 */
export function hasMoreAfter(
  pagination: ApiPagination | undefined,
  receivedCount: number,
  limit: number,
  fallbackPage: number
): boolean {
  if (pagination) {
    return responsePage(pagination, fallbackPage) < pagination.total_pages;
  }
  return receivedCount >= limit;
}

/**
 * Appended rows, skipping any id already present — including one repeated
 * *within* `incoming`.
 *
 * The intra-batch case is not hypothetical: `/posts/` can return the same post
 * twice in one response, which is why the code this replaces deduped page 1
 * against itself with a `findIndex` before storing it. The first version of this
 * helper built its `seen` set from `previous` only and so dropped that
 * behaviour; the test that found it is "a duplicate *within* page 1 is dropped
 * too".
 *
 * The first copy wins, so an earlier page's row is never replaced by a later
 * page's — relevant because these endpoints re-order under concurrent writes.
 */
export function appendUniqueById<T extends { id: number | string }>(
  previous: readonly T[],
  incoming: readonly T[]
): T[] {
  const seen = new Set(previous.map((row) => row.id));
  const added: T[] = [];
  for (const row of incoming) {
    if (seen.has(row.id)) continue;
    seen.add(row.id);
    added.push(row);
  }
  return [...previous, ...added];
}

/**
 * The page cursor for a filtered list.
 *
 * `resetSignature` is a string the caller builds from everything that
 * invalidates the accumulated list — search text, filter values, the selected
 * tab. When it changes the cursor returns to page 1 *during* the render that
 * carries the new signature, so no request is ever issued for page 3 of the
 * previous filter.
 */
export function usePageCursor(resetSignature: string) {
  const [page, setPage] = useState(1);
  const [actedOn, setActedOn] = useState(resetSignature);

  if (actedOn !== resetSignature) {
    setActedOn(resetSignature);
    setPage(1);
  }

  return {
    page: actedOn === resetSignature ? page : 1,
    /** Advance one page. The caller guards on `hasMore` / `isFetching`. */
    nextPage: () => setPage((previous) => previous + 1),
    /** Back to page 1 without waiting for the signature to change. */
    resetPage: () => setPage(1),
  };
}

/**
 * The accumulator's state, and the pure function that advances it.
 *
 * Extracted from the hook so the seven behaviours paging has to get right can be
 * asserted as a table rather than inferred from a component:
 *
 *  1. a filter change while a request is in flight;
 *  2. a stale response describing the previous query;
 *  3. a retry — the same page arriving twice;
 *  4. duplicate rows, within one response and across pages;
 *  5. the last page;
 *  6. a page arriving out of order;
 *  7. the order rows are rendered in.
 *
 * All seven are covered in `tests/pagedList.test.ts`.
 */
export interface PagedState<T> {
  /** The filter signature these rows belong to. */
  signature: string;
  /** Pages already folded in, so a retry of page *n* cannot append twice. */
  merged: number[];
  /**
   * The exact response object last folded in.
   *
   * Identity, not contents. React Query hands out a new object for every fetch
   * result and the same one on every re-render in between, which is precisely
   * the distinction this has to make: a re-render must be a no-op, while a
   * *refetch* that returns page 1 again must reload the list.
   *
   * `merged` alone cannot tell those apart, and getting it wrong is not
   * theoretical — with `merged` as the only guard, `refetch()` after the reader
   * had scrolled to page 2 was skipped entirely, because page 1 was already in
   * the set. Every caller that refetches after a delete or an attendance change
   * would have kept showing the deleted row.
   */
  lastResponse?: unknown;
  items: T[];
  hasMore: boolean;
}

export function initialPagedState<T>(signature: string): PagedState<T> {
  return { signature, merged: [], items: [], hasMore: true };
}

/** Everything the accumulator needs for one render. */
export interface PagedInput<T extends { id: number | string }> {
  /** Changing this invalidates the accumulated rows — see `usePageCursor`. */
  resetSignature: string;
  response: ApiResponse<T[]> | undefined;
  isFetching: boolean;
  /** The page size, used only when the endpoint sends no pagination block. */
  limit: number;
  /** For endpoints that can return one row twice. */
  dedupeById?: boolean;
  /**
   * Keep the previous filter's rows on screen until the new page 1 arrives.
   *
   * Off by default, because a list that shows the old filter's results under a
   * new filter is misleading. On for a picker whose search box has its own
   * spinner, where an empty list would be read as "no matches" instead of
   * "still looking".
   */
  keepPreviousWhileFetching?: boolean;
}

/**
 * The next accumulator state, or `null` when nothing has to change.
 *
 * Returning `null` for "no change" is what keeps the render-time adjustment from
 * looping: React re-runs the render after a `setState` during render, and an
 * unconditional write would never settle.
 */
export function nextPagedState<T extends { id: number | string }>(
  state: PagedState<T>,
  input: PagedInput<T>
): PagedState<T> | null {
  const {
    resetSignature,
    response,
    isFetching,
    limit,
    dedupeById,
    keepPreviousWhileFetching,
  } = input;
  const signatureChanged = state.signature !== resetSignature;

  /*
   * A response that is still being refetched describes the *previous* query.
   * Merging it would attribute the old filter's rows to the new one, which is
   * the stale-response case — and the reason the page number comes from the
   * response below rather than from the caller's page state.
   */
  const rows = !isFetching && response?.data ? response.data : undefined;
  const pagination = response?.meta?.pagination;
  const page = rows ? responsePage(pagination, 1) : 0;

  /*
   * Two different "already handled" questions, and both have to be asked.
   *
   * A re-render delivers the *same* response object, which is never merged
   * twice. A new object carrying page 1 is a reload — a refetch, a
   * pull-to-refresh, or an invalidation after a write — and must replace the
   * list even though page 1 is in `merged`. A new object carrying page *n > 1*
   * is a retry of an append, and `merged` is what stops that doubling the list.
   */
  const isNewResponse = Boolean(rows) && response !== state.lastResponse;
  const unmerged =
    isNewResponse && (page === 1 || !state.merged.includes(page));

  if (!signatureChanged && !unmerged) return null;

  /*
   * On a signature change the merged set always restarts, so the new filter's
   * page 1 replaces rather than appends. What happens to the *visible* rows in
   * the meantime is the caller's choice:
   *
   * - by default they are cleared, so a filter change cannot show one frame of
   *   the previous filter's results;
   * - with `keepPreviousWhileFetching` they stay until the new page 1 lands,
   *   which is what a search inside a picker modal wants — there the spinner
   *   beside the search icon signals the in-flight request and an empty list
   *   would read as "no matches".
   */
  const base = signatureChanged
    ? {
        merged: [] as number[],
        items: keepPreviousWhileFetching ? state.items : ([] as T[]),
      }
    : { merged: state.merged, items: state.items };

  if (!rows) {
    return {
      signature: resetSignature,
      ...base,
      lastResponse: undefined,
      /* `hasMore` stays optimistic: the new filter has not answered yet, so
         "no more" would disable the loader before the first page arrives. */
      hasMore: true,
    };
  }

  /*
   * Order is preserved exactly as the endpoint sent it: page 1 replaces,
   * later pages append to the tail. `merged` is not sorted and is not used for
   * ordering — a page that arrives out of sequence is appended where it lands,
   * which is what the call sites this replaces did.
   *
   * On page 1 with `dedupeById` the dedupe still runs — against an empty list —
   * because at least one endpoint returns the same row twice *within* one
   * response, and the code this replaces handled that case explicitly.
   */
  const items =
    page === 1
      ? dedupeById
        ? appendUniqueById([], rows)
        : [...rows]
      : dedupeById
        ? appendUniqueById(base.items, rows)
        : [...base.items, ...rows];

  return {
    signature: resetSignature,
    /* Page 1 restarts the merged set: a refetch of page 1 is a reload, not an
       append, so pages 2..n must become mergeable again. */
    merged: page === 1 ? [1] : [...base.merged, page],
    lastResponse: response,
    items,
    hasMore: hasMoreAfter(pagination, rows.length, limit, page),
  };
}

/**
 * The rows accumulated so far, and whether another page exists.
 *
 * Give it the same `resetSignature` as `usePageCursor`: a change clears the rows
 * in the same render that resets the cursor. `dedupeById` is for the endpoints
 * whose ordering is not stable under concurrent writes, where the same row can
 * legitimately arrive on two pages.
 */
export function usePagedItems<T extends { id: number | string }>(
  input: PagedInput<T>
): {
  items: T[];
  hasMore: boolean;
  /**
   * Rewrite the merged rows in place, for an optimistic edit.
   *
   * The attendance table needs this: marking a volunteer present patches
   * `date_wise_attended` on the row it already holds rather than refetching
   * the page. The updater is applied to the merged list and leaves the paging
   * bookkeeping — the signature, the merged-page set, the response identity —
   * untouched, so a patch cannot make the next response look like a new page.
   *
   * It must stay a *pure* row transform. Anything that changes which rows
   * exist belongs in the reducer, not here.
   */
  patchItems: (updater: (rows: T[]) => T[]) => void;
} {
  const [state, setState] = useState<PagedState<T>>(() =>
    initialPagedState(input.resetSignature)
  );

  const next = nextPagedState(state, input);
  if (next) setState(next);

  /* During the discarded render, report the state the reducer just produced
     rather than the previous filter's rows — which is the stale frame this
     whole module replaces. */
  const current = next ?? state;

  const patchItems = useCallback((updater: (rows: T[]) => T[]) => {
    setState((previous) => ({ ...previous, items: updater(previous.items) }));
  }, []);

  return { items: current.items, hasMore: current.hasMore, patchItems };
}
