import { useState } from "react";

export const useInfiniteScroll = (tableRef: any, search: any, filters: any) => {
  const [searchText, setSearchText] = useState("");
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [total, setTotal] = useState(0);
  const [columns, setColumns] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);

  const onSearchText = (newSearchText: any) => {
    setSearchText(newSearchText);
    if (window.typingTime) {
      clearTimeout(window.typingTime);
    }

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

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

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

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

  return {
    onSearchText,
    onChangePage,
    setTotal,
    onChangeColumns,
    setColumns,
    onSelectedItems,
    setSelectedItems,
    setSearchText,
    infiniteScroll: true,
    searchText,
    total,
    columns,
    selectedItems,
  };
};
