"use client";

import {
  usePageCursor,
  usePagedItems,
} from "@/features/shared/pagedList";
import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { getLearnServeRegistrations } from "@/features/opportunities/services/learnServe";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { type RegisteredUser } from "./learnServeRegisterListTypes";

/**
 * A development opportunity's registrations, accumulated a page at a time.
 *
 * Shared by the two screens that show them: the read-only list, and the one that
 * also marks attendance. They had the same 40 lines each, down to the query key.
 *
 * Deliberately **not** `useInfiniteQuery`, and this is the individual judgement
 * the review brief asked for rather than a blanket rule. The attendance screen
 * mutates accumulated rows in place when a batch is marked present — to avoid a
 * refetch race that flashed the loader over a table the organizer had just
 * ticked — and it auto-selects rows on pages that arrive while select-all is in
 * force. Both need a writable array, which `useInfiniteQuery`'s cache is not.
 * Converting it would be a behaviour change dressed as a refactor.
 *
 * `mergedPagesRef` is what makes the accumulation idempotent: React Query can
 * re-deliver the same page object on a refetch or a remount, and without it those
 * rows would be appended twice.
 */
export function usePagedRegistrations({
  opportunityId,
  limit = 10,
  onReset,
}: {
  opportunityId: string | undefined;
  limit?: number;
  /** Called whenever the list is thrown away — a search, or a deletion. */
  onReset?: () => void;
}) {
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);

  /*
   * `onReset` is held the same way, and for the same reason: `resetList` must
   * keep a stable identity, because the effect below calls it whenever the
   * search changes. Listing `onReset` in the dependencies instead would give
   * `resetList` a new identity on every render for any caller passing an
   * inline callback, and that effect would then reset the list continuously.
   * The ref makes the empty dependency list honest rather than suppressed.
   */
  const onResetRef = useRef(onReset);
  useEffect(() => {
    onResetRef.current = onReset;
  }, [onReset]);

  /*
   * Paging goes through `features/shared/pagedList.ts`.
   *
   * The cursor returns to page 1 during the render that carries a new
   * `resetSignature`, and the reducer re-merges from page 1 — so dropping the
   * accumulated rows is no longer something to *do*, which is what removed the
   * reset effect, the merge effect and the `mergedPagesRef` bookkeeping. What
   * remains of `resetList` is the caller's own side effect (clearing the
   * selection) plus a page-1 refetch.
   */
  const resetSignature = debouncedSearch;
  const { page: currentPage, nextPage, resetPage } = usePageCursor(resetSignature);

  const {
    data: response,
    isLoading,
    isFetching,
    isError,
    error,
    refetch,
  } = useQuery({
    queryKey: [
      "learn-serve-registrations",
      opportunityId,
      currentPage,
      limit,
      debouncedSearch,
    ],
    queryFn: () =>
      getLearnServeRegistrations({
        opportunity_id: opportunityId as string,
        page: currentPage,
        limit,
        search: debouncedSearch,
      }),
    enabled: Boolean(opportunityId),
  });

  const {
    items: rows,
    hasMore,
    patchItems: setRows,
  } = usePagedItems<RegisteredUser>({
    resetSignature,
    response,
    isFetching,
    limit,
    dedupeById: true,
  });

  const loadMore = useCallback(() => {
    // Guard: don't load next page while the list is empty (e.g. right after a reset)
    if (hasMore && !isFetching && rows.length > 0) {
      nextPage();
    }
  }, [hasMore, isFetching, rows.length, nextPage]);

  /* The caller's reset: clear its selection and go back to page 1. The rows
     themselves follow from the cursor, not from being emptied here. */
  const resetList = useCallback(() => {
    resetPage();
    onResetRef.current?.();
  }, [resetPage]);

  return {
    rows,
    setRows,
    hasMore,
    isLoading,
    isFetching,
    debouncedSearch,
    searchQuery,
    setSearchQuery,
    loadMore,
    refetch,
    resetList,
    /** A failed read with nothing to show — an error, not an empty list. */
    loadError: isError && rows.length === 0 ? (error ?? new Error("load")) : null,
  };
}
