"use client";

import {
  usePageCursor,
  usePagedItems,
} from "@/features/shared/pagedList";
import type { UntypedRow } from "./volunteerListHelpers";
import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  refreshVolunteerRegistrations,
  volunteerRegistrationsKey,
} from "./volunteerRegistrationsRefresh";
import { getVolunteerRegistrations } from "@/features/opportunities/services/registrations";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";

/** The container the table scrolls inside; named so the auto-load can measure it. */
const SCROLL_CONTAINER_ID = "registrations-scroll-container";

/**
 * A volunteering opportunity's registrations, paged and filterable by role.
 *
 * Kept separate from `usePagedRegistrations` (the development-opportunity one)
 * rather than merged: a different endpoint, a role filter in the query key, and
 * one behaviour the other list does not have — the **auto-load** below.
 *
 * That auto-load exists because the table sits in a fixed-height box. If the
 * first page does not overflow it there is no scrollbar, so nothing can trigger
 * the next page and the list appears to end at ten rows. `isAutoLoadingRef`
 * plus the 1.5s release is what stops that measurement from looping.
 */
export function useVolunteerRegistrationsList({
  opportunityId,
  roles,
}: {
  opportunityId: string | undefined;
  roles: number[] | undefined;
}) {
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedSearch = useDebouncedValue(searchQuery);

  const isAutoLoadingRef = useRef(false);

  /*
   * Paging now goes through `features/shared/pagedList.ts` instead of a
   * hand-rolled merge.
   *
   * Three effects went with it: the reset on a search/filter change (now
   * implied by `resetSignature`), the per-page merge (now the primitive's
   * reducer, which runs during render), and the ref assignment that fed the
   * `onPageMerged` callback. That callback is gone entirely — "select all"
   * stays sticky because `useVolunteerAttendance` derives the selection from
   * every loaded row rather than being told about each page.
   *
   * `patchItems` is what kept this hook from taking the primitive before: the
   * attendance flow patches rows in place after marking someone present.
   */
  /* The signature is everything that invalidates the accumulated list; the
     cursor returns to page 1 during the render that carries a new one, so no
     request is ever issued for page 3 of the previous filter. */
  const resetSignature = `${debouncedSearch}|${(roles ?? []).join(",")}`;
  const { page, nextPage, resetPage } = usePageCursor(resetSignature);
  const queryClient = useQueryClient();

  const registrationsQuery = useQuery({
    queryKey: [
      ...volunteerRegistrationsKey(opportunityId),
      page,
      roles,
      debouncedSearch,
    ],
    queryFn: () =>
      getVolunteerRegistrations({
        opportunity_id: opportunityId,
        page,
        limit: 10,
        roles,
        search: debouncedSearch,
      }),
    enabled: Boolean(opportunityId),
  });

  const registrations = registrationsQuery.data;
  const fetchingRegistrations = registrationsQuery.isFetching;

  const {
    items: allRegistrations,
    hasMore: hasMoreRegistrations,
    patchItems: patchRegistrations,
  } = usePagedItems<UntypedRow>({
    resetSignature,
    response: registrations,
    isFetching: fetchingRegistrations,
    limit: 10,
  });

  // Keep the last settled table visible while a new search is loading.
  // Scope the snapshot to the opportunity so navigation never shows another roster.
  const [settled, setSettled] = useState({ opportunityId, rows: allRegistrations });
  if (!fetchingRegistrations && (settled.rows !== allRegistrations || settled.opportunityId !== opportunityId)) {
    setSettled({ opportunityId, rows: allRegistrations });
  }
  const visibleRegistrations = fetchingRegistrations && settled.opportunityId === opportunityId
    ? settled.rows : allRegistrations;

  const resetAndRefetchRegistrations = () =>
    refreshVolunteerRegistrations(queryClient, opportunityId, resetPage);

  const loadMoreRegistrations = useCallback(() => {
    // Don't advance while the list is empty (e.g. right after a reset)
    if (
      hasMoreRegistrations &&
      !fetchingRegistrations &&
      allRegistrations.length > 0
    ) {
      nextPage();
    }
  }, [
    hasMoreRegistrations,
    fetchingRegistrations,
    allRegistrations.length,
    nextPage,
  ]);

  // The table lives in a fixed-height box; if the first page doesn't overflow it
  // there's nothing to scroll, so pull the next page automatically.
  useEffect(() => {
    if (
      fetchingRegistrations ||
      !hasMoreRegistrations ||
      allRegistrations.length === 0 ||
      isAutoLoadingRef.current
    ) {
      return;
    }

    const timeoutId = setTimeout(() => {
      const container = document.getElementById(SCROLL_CONTAINER_ID);
      if (!container || isAutoLoadingRef.current) return;

      if (container.scrollHeight <= container.clientHeight) {
        isAutoLoadingRef.current = true;
        loadMoreRegistrations();
        setTimeout(() => {
          isAutoLoadingRef.current = false;
        }, 1500);
      }
    }, 200);

    return () => clearTimeout(timeoutId);
  }, [
    allRegistrations,
    fetchingRegistrations,
    hasMoreRegistrations,
    loadMoreRegistrations,
  ]);

  return {
    registrations,
    fetchingRegistrations,
    allRegistrations: visibleRegistrations,
    patchRegistrations,
    hasMoreRegistrations,
    debouncedSearch,
    isSearching: searchQuery !== debouncedSearch || fetchingRegistrations,
    setSearchQuery,
    loadMoreRegistrations,
    resetAndRefetchRegistrations,
    isLoading: registrationsQuery.isLoading,
    /** A failed read with nothing to show — an error, not "nobody registered". */
    loadError:
      registrationsQuery.isError && allRegistrations.length === 0
        ? (registrationsQuery.error ?? new Error("load"))
        : null,
    retryRegistrations: () => void registrationsQuery.refetch(),
  };
}
