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

import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { usePagination } from "./use-pagination";

export const usePaginationSyncWithLocation = (
  initialPageIndex: number = INITIAL_PAGE_INDEX,
  initialPageSize: number = INITIAL_PAGE_SIZE
) => {
  const [urlSearchParams, setUrlSearchParams] = useSearchParams();

  const urlParamPageIndex: string | null = urlSearchParams.get("page_index");
  const urlParamPageSize: string | null = urlSearchParams.get("page_size");

  const calculatedPageIndex = useMemo(() => {
    const parsedPageIndex = Number.parseInt(urlParamPageIndex ?? "", 10);
    let result = !Number.isNaN(parsedPageIndex) ? parsedPageIndex : initialPageIndex;

    if (result < initialPageIndex) {
      result = initialPageIndex;
    }

    return result;
  }, [urlParamPageIndex, initialPageIndex]);

  const calculatedPageSize = useMemo(() => {
    const parsedPageSize = Number.parseInt(urlParamPageSize ?? "", 10);
    let result = !Number.isNaN(parsedPageSize) ? parsedPageSize : initialPageSize;
    if (result < MIN_PAGE_SIZE || result > MAX_PAGE_SIZE) {
      result = initialPageSize;
    }
    return result;
  }, [urlParamPageSize, initialPageSize]);

  const [pagination, setPagination] = usePagination(calculatedPageIndex, calculatedPageSize);

  const updatePagination = (newPagination: any) => {
    const _validatedPagination = setPagination(newPagination);

    setUrlSearchParams({
      //...actualSearchParam,
      page_index: String(_validatedPagination.pageIndex),
      page_size: String(_validatedPagination.pageSize),
    });
  };

  return [pagination, updatePagination] as const;
};
