"use client";

import { unassignedRoleOption } from "../roleCapacity";
import { getOpportunityById } from "../services/opportunities";
import type { VolunteerOpportunityRoleRecord } from "@/features/opportunities/rolesAndTeamsRecord";
import { useQuery } from "@tanstack/react-query";
import { getRolesOfOpportunity } from "@/features/opportunities/services/roles";
import { shouldLoadNextMenuPageFromEvent } from "@/features/shared/menuPaging";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";

/** A role as the API returns it, with its two localized columns. */
/**
 * One role the picker offers.
 *
 * The real record rather than `{ id, remaining_slots?, [key: string]: unknown }`
 * — that index signature is what let `rolesData.data as OpportunityRole[]`
 * pass without ever being checked against the resource.
 */
export type OpportunityRole = VolunteerOpportunityRoleRecord;

export interface OpportunityRoleOption {
  label: string;
  value: string;
  remaining_slots?: number;
  instructions: string;
}

/**
 * The roles an opportunity offers, ten at a time as the menu is scrolled.
 *
 * The options carry `remaining_slots` and `instructions` alongside the label so
 * selecting one can fill the two read-only fields beside the picker without a
 * second lookup — which is why this returns options rather than plain strings.
 */
export function useOpportunityRolePicker({
  opportunityId,
  selectedLanguage,
}: {
  opportunityId: string;
  selectedLanguage: string;
}) {
  /*
   * Roles arrive a page at a time and accumulate as the menu is scrolled.
   *
   * `usePageCursor` + `usePagedItems` rather than a page number, a `rolesList`
   * mirror and an effect that appended to it. Besides the effect, the mirror
   * had two faults the shared reducer does not: the append was keyed on nothing
   * but row ids, so a *refetch* of page 1 after a role was edited appended
   * nothing and the stale row stayed on screen; and switching opportunity never
   * cleared the list, so the previous opportunity's roles stayed selectable.
   * The reducer keys on response identity and on `opportunityId` as the reset
   * signature, which answers both.
   */
  const { page, nextPage } = usePageCursor(opportunityId);

  const {
    data: rolesData,
    isLoading: rolesLoading,
    isFetching,
  } = useQuery({
    queryKey: ["opportunity-roles", opportunityId, page],
    queryFn: () =>
      getRolesOfOpportunity({
        opportunity_id: opportunityId,
        page,
        limit: 10,
      }),
    enabled: Boolean(opportunityId),
  });

  const { items: rolesList } = usePagedItems<OpportunityRole>({
    resetSignature: opportunityId,
    response: rolesData,
    isFetching,
    limit: 10,
    dedupeById: true,
  });

  /*
   * Was `scrollHeight - scrollTop === clientHeight` with no last-page guard, so
   * the menu both stopped paging on a fractional device pixel ratio and, when it
   * did page, ran past the last page firing an empty request per scroll. See
   * `shouldLoadNextMenuPage`.
   */
  const handleMenuScroll = (event: React.UIEvent<HTMLDivElement>) => {
    if (
      shouldLoadNextMenuPageFromEvent(
        event,
        rolesLoading,
        rolesData?.meta?.pagination
      )
    ) {
      nextPage();
    }
  };

  /*
   * Picked by an explicit branch rather than `role[`role_name_${language}`]`.
   * Two reasons, both of which the old index signature hid:
   *
   * - the resource has exactly `role_name_en` / `role_name_ar`, so any other
   *   language value silently produced `undefined`;
   * - both columns are **nullable**, and `String(null)` is the four-character
   *   string `"null"` — which is what the dropdown would have shown for a role
   *   saved without a name in the active language.
   */
  const opportunity = useQuery({ queryKey: ["opportunity-details", opportunityId], queryFn: () => getOpportunityById(opportunityId), enabled: Boolean(opportunityId) });
  const unassigned = unassignedRoleOption(opportunity.data?.data?.unassigned_slots_remaining, selectedLanguage);
  const isArabic = selectedLanguage === "ar";
  const roleOptions: OpportunityRoleOption[] = rolesList.map((role) => ({
    label: (isArabic ? role.role_name_ar : role.role_name_en) ?? "",
    value: String(role.id),
    remaining_slots: role.remaining_slots,
    instructions: (isArabic ? role.instructions_ar : role.instructions_en) ?? "",
  }));

  return { roleOptions: unassigned ? [unassigned, ...roleOptions] : roleOptions, rolesLoading: rolesLoading || opportunity.isLoading, handleMenuScroll };
}
