"use client";

import { useState } from "react";
import { usePagedRegistrations } from "./usePagedRegistrations";
import {
  EMPTY_SELECTION,
  type SelectionState,
} from "./registrationSelection";

/**
 * The attendance screen's registration list: `usePagedRegistrations` plus the
 * one thing that screen needs and the read-only list does not — keeping
 * "select all" in force across pages that have not loaded yet.
 *
 * A search or a delete throws the list away, so the selection goes with it: the
 * rows the organizer ticked may not even be in the new results.
 */
export function useLearnServeRegistrationsList({
  opportunityId,
  setSelection,
}: {
  opportunityId: string | undefined;
  setSelection: (next: SelectionState) => void;
}) {
  /*
   * No `onPageMerged`. "Select all" stays sticky across pages because the
   * caller derives the selection from every loaded row through
   * `effectiveSelectedUsers` — there is nothing to fold in per page, and so
   * nothing that has to reach back into the parent's state while the paging
   * hook is mid-merge.
   */
  const paged = usePagedRegistrations({
    opportunityId,
    onReset: () => setSelection(EMPTY_SELECTION),
  });

  const [settled, setSettled] = useState({ opportunityId, rows: paged.rows, loaded: false });
  if (!paged.isFetching && !paged.isLoading &&
      (settled.rows !== paged.rows || settled.opportunityId !== opportunityId || !settled.loaded)) {
    setSettled({ opportunityId, rows: paged.rows, loaded: true });
  }
  const hasLoaded = settled.opportunityId === opportunityId && settled.loaded;

  return {
    allRegisteredUsers: paged.isFetching && hasLoaded ? settled.rows : paged.rows,
    isSearching: paged.searchQuery !== paged.debouncedSearch || paged.isFetching,
    showInitialLoader: paged.isLoading && !hasLoaded,
    setAllRegisteredUsers: paged.setRows,
    hasMore: paged.hasMore,
    isLoading: paged.isLoading,
    isFetching: paged.isFetching,
    debouncedSearch: paged.debouncedSearch,
    setSearchQuery: paged.setSearchQuery,
    loadMoreRegistrations: paged.loadMore,
    refetchRegistrations: paged.refetch,
    resetList: paged.resetList,
    loadError: paged.loadError,
  };
}
