import { ref, computed, type ComputedRef, type Ref } from "vue";

export type BulkSelectionState = {
  selectedIds: Ref<Set<unknown>>;
  allSelected: ComputedRef<boolean>;
  isSelectAllRecords: Ref<boolean>;
  toggle: (id: unknown) => void;
  toggleAll: () => void;
  selectAllRecords: () => void;
  clear: () => void;
};

export function useBulkSelection(
  rows: Ref<Record<string, unknown>[]>,
): BulkSelectionState {
  const selectedIds = ref<Set<unknown>>(new Set());
  const isSelectAllRecords = ref(false);

  const allSelected = computed(
    () =>
      rows.value.length > 0 &&
      rows.value.every((r) => selectedIds.value.has(r.id)),
  );

  function toggle(id: unknown): void {
    isSelectAllRecords.value = false;
    const next = new Set(selectedIds.value);
    if (next.has(id)) {
      next.delete(id);
    } else {
      next.add(id);
    }
    selectedIds.value = next;
  }

  function toggleAll(): void {
    isSelectAllRecords.value = false;
    if (allSelected.value) {
      selectedIds.value = new Set();
    } else {
      selectedIds.value = new Set(rows.value.map((r) => r.id));
    }
  }

  function selectAllRecords(): void {
    isSelectAllRecords.value = true;
  }

  function clear(): void {
    selectedIds.value = new Set();
    isSelectAllRecords.value = false;
  }

  return {
    selectedIds,
    allSelected,
    isSelectAllRecords,
    toggle,
    toggleAll,
    selectAllRecords,
    clear,
  };
}
