"use client";

import type { ApiResponse } from "@/lib/api/types";
import type { OpportunityCardRecord } from "@/features/opportunities/opportunityRecord";
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/lib/api/client";
import { useResponsiveValue } from "@/hooks/useViewportWidth";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";
import { type AllOpportunitiesFiltersData } from "./opportunityFilters";
import {
  buildOpportunityListParams,
  opportunityListEndpoint,
} from "./opportunityListQueryParams";

/**
 * The opportunity list's own paging.
 *
 * `limit` is recomputed from the viewport so a page always fills a whole number
 * of grid rows, and changing it restarts paging. That used to be the reason
 * this hook fetched imperatively through `apiClient` and kept its own
 * `allOpportunities` / `hasMore` / `isLoading` / `totalResults` state — a cache
 * keyed on a limit that changes with the window was thought to strand
 * half-rows in it.
 *
 * It does not: a different limit is simply a different query key, and `limit`
 * is part of the reset signature, so the accumulated rows restart with it. So
 * the request goes through React Query like every other list, the viewport
 * measurement goes through `useViewportWidth` (an external store, not a resize
 * effect writing state), and the accumulation goes through
 * `features/shared/pagedList` — which is what removes the two
 * `react-hooks/set-state-in-effect` reports this hook used to carry, the
 * second of which fired a fetch from an effect body on every filter change.
 */
export function useOpportunitiesFeed({
  isLearnServe,
  searchQuery,
  filters,
}: {
  isLearnServe?: boolean;
  searchQuery?: string;
  filters?: AllOpportunitiesFiltersData;
}) {
  const queryClient = useQueryClient();

  /*
   * A page that fills whole grid rows: three columns take 9, two take 8, one
   * takes 9. The pre-measurement value is the one-column answer, which is the
   * number the old `useState(calculateOptimalLimit(1))` started at — so the
   * first request is unchanged.
   */
  const limit = useResponsiveValue(
    [
      { minWidth: 1200, value: 9 },
      { minWidth: 768, value: 8 },
      { minWidth: 0, value: 9 },
    ],
    9
  );

  /* Everything that invalidates the accumulated rows. The filters are an
     object, so the signature is their serialization rather than their
     identity — the screens rebuild that object on every render. */
  const resetSignature = JSON.stringify({
    isLearnServe: Boolean(isLearnServe),
    searchQuery: searchQuery ?? "",
    filters: filters ?? null,
    limit,
  });

  const { page, nextPage, resetPage } = usePageCursor(resetSignature);

  const { data, isFetching, isError, error, refetch: retryPage } = useQuery({
    queryKey: [
      "opportunities-feed",
      Boolean(isLearnServe),
      searchQuery ?? "",
      filters ?? null,
      limit,
      page,
    ],
    queryFn: () =>
      apiClient
        .get<ApiResponse<OpportunityCardRecord[]>>(
          opportunityListEndpoint(isLearnServe),
          {
            params: buildOpportunityListParams({
              page,
              limit,
              searchQuery,
              filters,
              isLearnServe,
            }),
          }
        )
        .then((response) => response.data),
  });

  /*
   * The accumulated feed. `OpportunityCardRecord[]` — the two website card
   * resources — because every endpoint this hook calls is one of the
   * opportunity list routes.
   */
  const { items: allOpportunities, hasMore } = usePagedItems<
    OpportunityCardRecord
  >({
    resetSignature,
    response: data,
    isFetching,
    limit,
    /* These endpoints re-order under concurrent writes, so the same card can
       legitimately arrive on two pages. */
    dedupeById: true,
  });

  /*
   * `meta.pagination.total` is the count across every page, not just the ones
   * loaded so far — that's the number the result line has to show.
   *
   * Held rather than read straight off `data`, because `data` is `undefined`
   * while the next page is in flight and the count must not blink out from
   * under the reader. Updated on each new response — including to `null` when
   * a response carries no pagination block — which is exactly what the
   * imperative version did.
   */
  const [totalResults, setTotalResults] = useState<number | null>(null);
  const [countedResponse, setCountedResponse] = useState<typeof data>(undefined);
  if (data && data !== countedResponse) {
    setCountedResponse(data);
    const total = data.meta?.pagination?.total;
    setTotalResults(typeof total === "number" ? total : null);
  }

  const loadMore = () => {
    if (!hasMore || isFetching) return;
    /* No scroll here. This used to dispatch `learn-serve-page-change`, and the
       development list answered it by scrolling to the top of the grid — a
       leftover from page buttons that, under infinite scroll, threw the reader
       back up every time the next page arrived. The new rows append below
       where they already are. */
    nextPage();
  };

  /*
   * Back to page 1 and drop every cached page of this feed, so the next page-1
   * response is a new object and the reducer replaces the list with it. Used
   * after a delete, where refetching only the page the reader happens to be on
   * would leave the removed card above it.
   */
  const refetch = () => {
    resetPage();
    void queryClient.invalidateQueries({ queryKey: ["opportunities-feed"] });
  };

  return {
    allOpportunities,
    hasMore,
    isLoading: isFetching,
    totalResults,
    loadMore,
    refetch,
    /* A failed page used to read as «لا توجد فرص» on page 1 and as an endless
       spinner on a later page (the infinite scroller never asks again once a
       request it triggered adds no rows). The failure and a retry of exactly
       that page are surfaced instead. */
    isError: isError && !isFetching,
    error,
    retry: () => { void retryPage(); },
  };
}
