import { useEffect, useRef } from 'react';

type SelectionLifecycleTarget = {
  allRows: boolean;
  excludedIds: Set<string>;
  reset: () => void;
};

type UseApprovalSelectionLifecycleArgs = {
  selection: SelectionLifecycleTarget;
  debouncedSearch: string;
  orderBy: string | undefined;
  order: string;
  totalMatchingCount: number;
};

/**
 * Owns the change-detection resets for a selection:
 *  - clear when the active search changes
 *  - clear when the sort changes (visible order shifts → confusing UX)
 *  - exit allRows mode once the user has individually excluded every match
 *
 * User-action-driven resets (filter apply, tab switch) stay at the call site
 * — they are not change-detection and don't belong here.
 */
export const useApprovalSelectionLifecycle = ({
  selection,
  debouncedSearch,
  orderBy,
  order,
  totalMatchingCount,
}: UseApprovalSelectionLifecycleArgs) => {
  const searchInitRef = useRef(true);
  // biome-ignore lint/correctness/useExhaustiveDependencies: debouncedSearch is the change trigger, not used in the body.
  useEffect(() => {
    if (searchInitRef.current) {
      searchInitRef.current = false;
      return;
    }
    selection.reset();
  }, [debouncedSearch, selection.reset]);

  const sortInitRef = useRef(true);
  // biome-ignore lint/correctness/useExhaustiveDependencies: orderBy/order are the change triggers, not used in the body.
  useEffect(() => {
    if (sortInitRef.current) {
      sortInitRef.current = false;
      return;
    }
    selection.reset();
  }, [orderBy, order, selection.reset]);

  useEffect(() => {
    if (
      selection.allRows &&
      totalMatchingCount > 0 &&
      selection.excludedIds.size >= totalMatchingCount
    ) {
      selection.reset();
    }
  }, [
    selection.allRows,
    selection.excludedIds.size,
    totalMatchingCount,
    selection.reset,
  ]);
};
