import { useState } from "react";

export const useNextTokenInfiniteScroll = (
  tableRef: any,
  search: any,
  filters: any,
  nextToken: any
) => {
  const [searchText, setSearchText] = useState("");
  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.setSelectedItems([]);
      setSelectedItems([]);
      onChangePage(newSearchText, true, null);
      window.typingTime = null;
    }, 500);
  };

  const onChangePage = (
    newSearchText = searchText,
    resetSearch = false,
    newNextToken = nextToken
  ) => {
    let newFilters = {
      ...filters,
      limit: 25,
      openSearch: newSearchText,
      resetSearch: resetSearch,
      nextToken: newNextToken,
    };

    search(newFilters);
  };

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

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

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