"use client";

import { useCallback, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  getAllOrganizations,
  type DirectoryOrganization,
} from "@/features/shared/services/directory";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import {
  mergeSponsorOptions,
  shouldLoadNextSponsorPage,
} from "./sponsorPaging";

interface Organization {
  id: string;
  full_name: string;
}

/** One sponsor as the opportunity payload carries it — nested, or just an id. */
export type SavedSponsor =
  | { id: number | string; full_name?: string | null; company_name?: string | null }
  | number
  | string
  | null;

/**
 * The sponsor picker's option list, shared by both publish forms.
 *
 * Three sources have to end up in one dropdown, which is the whole reason this
 * is not a single query:
 *
 *  1. a page of organizations, fetched ten at a time as the menu is scrolled;
 *  2. the sponsors already attached to the opportunity, which the API returns
 *     **either** as nested objects **or** as bare ids depending on the
 *     endpoint — so bare ids need a second, targeted fetch;
 *  3. whatever earlier pages already loaded.
 *
 * Without (2) an already-chosen sponsor that happens to sit on page 4 shows as
 * a blank selection until the user scrolls far enough to load it.
 */
export function useOpportunitySponsors(authToken: string | undefined) {
  const [preLoadedSponsors, setPreLoadedSponsors] = useState<Organization[]>([]);
  const [sponsorIdsToFetch, setSponsorIdsToFetch] = useState<number[]>([]);

  const [sponsorSearch, setSponsorSearch] = useState("");
  const search = useDebouncedValue(sponsorSearch.trim());
  const signature = `all-organizations|${search}`;
  const { page: currentPage, nextPage } = usePageCursor(signature);

  const {
    data: sponsorsData,
    isLoading: sponsorsLoading,
    isFetching: sponsorsFetching,
  } = useQuery({
    queryKey: ["all-organizations", "for-sponsorship", search, currentPage],
    /* `for_sponsorship`: the backend leaves volunteer teams out, and it never
       lists the caller's own organization (client answers p.1, item 5:
       sponsors are organizations only, never the organizer itself). The event
       form already sent it; these two forms did not, so teams were offered. */
    queryFn: () => getAllOrganizations({ name: search, for_sponsorship: 1, page: currentPage, limit: 10 }),
    enabled: Boolean(authToken),
  });

  const { data: sponsorsByIdsData } = useQuery({
    queryKey: ["organizations-by-ids", sponsorIdsToFetch],
    queryFn: () =>
      getAllOrganizations({
        ids: sponsorIdsToFetch.join(","),
        for_sponsorship: 1,
        page: 1,
        limit: 100,
      }),
    enabled: Boolean(authToken) && sponsorIdsToFetch.length > 0,
  });

  /**
   * Next page, on reaching the bottom of the open menu. The decision itself is
   * `shouldLoadNextSponsorPage`, which is where both of its rules — the scroll
   * tolerance and the last-page guard — are documented and tested.
   */
  const handleMenuScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const target = event.target as HTMLDivElement;
    const shouldLoad = shouldLoadNextSponsorPage({
      geometry: {
        scrollTop: target.scrollTop,
        clientHeight: target.clientHeight,
        scrollHeight: target.scrollHeight,
      },
      isLoading: sponsorsFetching || sponsorSearch.trim() !== search,
      pagination: sponsorsData?.meta?.pagination,
    });
    if (shouldLoad) nextPage();
  };

  /**
   * Seed from the loaded opportunity.
   *
   * A repost keeps its sponsors — unlike its images, they describe who is
   * backing the organizer rather than what happened on the day.
   */
  const seedFromSponsors = useCallback((saved: SavedSponsor[]) => {
    if (saved.length === 0) return;

    // Resolve every saved id through the eligibility-filtered endpoint. Legacy
    // nested records can include teams or the publisher itself; preloading
    // their labels would put those ineligible accounts back into the picker.
    setPreLoadedSponsors([]);
    setSponsorIdsToFetch([...new Set(saved.flatMap((value) => {
      const id = Number(typeof value === "object" && value !== null ? value.id : value);
      return Number.isSafeInteger(id) && id > 0 ? [id] : [];
    }))]);
  }, []);

  /*
   * The three sources, as derivations rather than three effects appending to a
   * shared `sponsorList` mirror.
   *
   * The first of those effects — the one that merged `preLoadedSponsors` into
   * the list — was redundant: `mergeSponsorOptions` below already takes
   * `preLoadedSponsors` as its first argument and wins ties, so copying them
   * into the list as well added nothing. It is gone rather than rewritten.
   *
   * The second was a `map` over one response, so it is a `useMemo`. Only the
   * third was genuine page-at-a-time accumulation, and that is what
   * `usePagedItems` does.
   */
  const { items: pagedSponsors } = usePagedItems<DirectoryOrganization>({
    resetSignature: signature,
    response: sponsorsData,
    isFetching: sponsorsFetching,
    limit: 10,
    dedupeById: true,
    keepPreviousWhileFetching: true,
  });

  const sponsorList = useMemo<Organization[]>(() => {
    const byIds = (sponsorsByIdsData?.data ?? []).map((org) => ({
      id: String(org.id),
      full_name: org.full_name || "",
    }));
    const paged = pagedSponsors.map((org) => ({
      id: String(org.id),
      full_name: org.full_name || "",
    }));
    /* Fetched-by-id first, then the scrolled pages — the order the effects
       produced, and the order `mergeSponsorOptions` needs to keep an attached
       sponsor's own label. Duplicates across the two are dropped there. */
    return [...byIds, ...paged];
  }, [sponsorsByIdsData, pagedSponsors]);

  /**
   * De-duplicated by id, with the already-attached sponsors inserted first so
   * a current selection always has a label even before its page loads. See
   * `mergeSponsorOptions` for why that order matters.
   */
  const sponsorOptions = useMemo(
    () => mergeSponsorOptions(preLoadedSponsors, sponsorList),
    [preLoadedSponsors, sponsorList]
  );

  // Keep selected labels available when a new search replaces the result page.
  const rememberSponsor = useCallback((option: { value: string; label: string } | null) => {
    if (!option) return;
    setPreLoadedSponsors(previous => previous.some(org => org.id === option.value)
      ? previous
      : [...previous, { id: option.value, full_name: option.label }]);
  }, []);

  return {
    sponsorOptions,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    seedFromSponsors,
    setSponsorSearch,
    rememberSponsor,
  };
}
