import {
  INITIAL_PAGE_INDEX,
  INITIAL_PAGE_SIZE,
  MAX_PAGE_SIZE,
  MIN_PAGE_SIZE,
} from "@shared/contexts";
import { PaginationState } from "@tanstack/react-table";
import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { usePagination } from "./usePagination";

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 = parseInt(urlParamPageIndex ?? "", 10);
    let result = !isNaN(parsedPageIndex) ? parsedPageIndex : initialPageIndex;

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

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

  const calculatedPageSize = useMemo(() => {
    const parsedPageSize = parseInt(urlParamPageSize ?? "", 10);
    let result = !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: PaginationState) => {
    const _validatedPagination = setPagination(newPagination);

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

  return [pagination, updatePagination] as const;
};
