import {
  INITIAL_PAGE_INDEX,
  INITIAL_PAGE_SIZE,
  MAX_PAGE_SIZE,
  MIN_PAGE_SIZE,
} from "@repo/rdx-criteria";
import { useState } from "react";

export const DEFAULT_PAGE_SIZES = [5, 10, 15, 30, 50, 75, 100];

export interface PaginationState {
  pageIndex: number;
  pageSize: number;
}

export const defaultPaginationState = {
  pageIndex: INITIAL_PAGE_INDEX,
  pageSize: INITIAL_PAGE_SIZE,
};

export const usePagination = (
  initialPageIndex: number = INITIAL_PAGE_INDEX,
  initialPageSize: number = INITIAL_PAGE_SIZE
) => {
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: initialPageIndex,
    pageSize: initialPageSize,
  });

  const updatePagination = (newPagination: PaginationState) => {
    // Realiza comprobaciones antes de actualizar el estado
    const validatedPagination = newPagination;

    if (validatedPagination.pageIndex < INITIAL_PAGE_INDEX) {
      validatedPagination.pageIndex = INITIAL_PAGE_INDEX;
    }

    if (newPagination.pageSize < MIN_PAGE_SIZE || newPagination.pageSize > MAX_PAGE_SIZE) {
      validatedPagination.pageSize = MIN_PAGE_SIZE;
    }

    setPagination((oldPagination) => ({
      ...oldPagination,
      pageIndex: newPagination.pageIndex,
      pageSize: newPagination.pageSize,
    }));

    return validatedPagination;
  };

  return [pagination, updatePagination] as const;
};
