import { useState, useEffect, useCallback } from 'react';

/**
 * Row selection for paginated list + export. Selection is scoped to the current page:
 * "select all" replaces the set with the current page's names; changing `resetKey` clears selection.
 */
export function useListPageSelection<T extends { name: string }>(pageRows: T[], resetKey: string | number) {
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());

  useEffect(() => {
    setSelectedRows(new Set());
  }, [resetKey]);

  const toggleRow = useCallback((name: string) => {
    setSelectedRows(prev => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name);
      else next.add(name);
      return next;
    });
  }, []);

  const toggleAllOnPage = useCallback(() => {
    setSelectedRows(prev => {
      const pageIds = pageRows.map(r => r.name);
      if (pageIds.length === 0) return new Set();
      const allOnPage = pageIds.every(id => prev.has(id));
      if (allOnPage) return new Set();
      return new Set(pageIds);
    });
  }, [pageRows]);

  const allOnPageSelected = pageRows.length > 0 && pageRows.every(r => selectedRows.has(r.name));
  const someOnPageSelected =
    pageRows.some(r => selectedRows.has(r.name)) && !allOnPageSelected;

  return {
    selectedRows,
    toggleRow,
    toggleAllOnPage,
    allOnPageSelected,
    someOnPageSelected,
  };
}
