import { computed, ref, watch } from "vue";

export const DEFAULT_PAGE_SIZE = 10;
export const PAGE_SIZE_OPTIONS = [10, 20, 50, 100];

export function usePagination(rowsRef, initialPageSize = DEFAULT_PAGE_SIZE) {
  const page = ref(1);
  const pageSize = ref(Number(initialPageSize || DEFAULT_PAGE_SIZE));
  const total = computed(() => rowsRef.value.length);
  const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)));
  const rows = computed(() => {
    const start = (page.value - 1) * pageSize.value;
    return rowsRef.value.slice(start, start + pageSize.value);
  });

  watch(rowsRef, () => {
    page.value = 1;
  });

  watch(pageSize, () => {
    page.value = 1;
  });

  watch([total, page, pageSize], () => {
    if (page.value > pageCount.value) {
      page.value = pageCount.value;
    }
    if (page.value < 1) {
      page.value = 1;
    }
  });

  return {
    page,
    pageSize,
    total,
    pageCount,
    rows
  };
}
