import { useEffect, useState } from "react";

export const usePagination = (
  tableRef: any,
  search: any,
  filters?: any,
) => {
  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const [columns, setColumns] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const [currentFilters, setCurrentFilters] = useState(filters);

  const onSearchText = (newSearchText: any) => {
    setSearchText(newSearchText);

    if (window.typingTime) {
      clearTimeout(window.typingTime);
    }

    window.typingTime = setTimeout(() => {
      tableRef?.current?.setPage(1);
      tableRef?.current?.setSelectedItems([]);
      setSelectedItems([]);
      onChangePage(1, rowsPerPage, newSearchText, true);
      window.typingTime = null;
    }, 500);
  };

  const onChangeSort = (newSort: any) => {
    let newFilters = {
      ...currentFilters,
      orderBy: newSort?.key,
      desc: newSort?.order === "desc" ? true : false,
    };
    search(newFilters);
    setCurrentFilters(newFilters);
  };

  const onChangePage = (
    newPage = 1,
    newRowsPerPage = rowsPerPage,
    newSearchText = searchText,
    resetSearch = false
  ) => {
    const newOffset = (newPage - 1) * newRowsPerPage;
    let newFilters = {
      ...currentFilters,
      openSearch: newSearchText,
      offset: newOffset,
      limit: newRowsPerPage,
      resetSearch: resetSearch,
    };
    search(newFilters);
    setPage(newPage);
    setCurrentFilters(newFilters);
  };

  const refresh = (_filters = {}) => {
    const newOffset =
      ((tableRef?.current?.page == 0 ? rowsPerPage : tableRef?.current?.page) -
        1) *
      rowsPerPage;
    let newFilters = {
      ...currentFilters,
      ..._filters,
      openSearch: searchText,
      offset: newOffset,
      limit: rowsPerPage,
      //resetSearch: resetSearch
    };
    search(newFilters);
    setCurrentFilters(newFilters);
  };

  const onChangeRowsPerPage = (newRowsPerPage: any) => {
    setRowsPerPage(newRowsPerPage);
    onChangePage(1, newRowsPerPage, searchText, true);
  };

  const onChangeColumns = (newColums: any) => {
    setColumns(newColums);
  };

  const onSelectedItems = (selectedItems: any) => {
    setSelectedItems(selectedItems);
  };

  const resetTable = () => {
    setSearchText("");
    setSelectedItems([]);
    onChangePage(1, 10, "", true);
    tableRef?.current?.setPage(1);
    tableRef?.current?.setSelectedItems([]);
  };

  return {
    onSearchText,
    onChangePage,
    onChangeSort,
    onChangeRowsPerPage,
    onChangeColumns,
    setColumns,
    onSelectedItems,
    setSelectedItems,
    setSearchText,
    resetTable,
    rowsPerPage,
    page,
    hideAllInPagination: false,
    infiniteScroll: false,
    searchText,
    columns,
    selectedItems,
    refresh,
    filters: {
      ...filters,
      openSearch: searchText,
    }
  };
};
