import { useState, useCallback } from 'react';

interface UseServerTableOptions {
  pageSize?: number;
}

/**
 * Centralizes the page-index + search-query state a server-paginated table
 * needs. Changing the search query resets paging back to page 0.
 */
export function useServerTable({ pageSize: initialPageSize = 10 }: UseServerTableOptions = {}) {
  const [pageIndex, setPageIndex] = useState(0);
  const [pageSize, setPageSizeInternal] = useState(initialPageSize);
  const [q, setQInternal] = useState('');

  const setQ = useCallback((value: string) => {
    setQInternal(value);
    setPageIndex(0);
  }, []);

  const setPageSize = useCallback((value: number) => {
    setPageSizeInternal(value);
    setPageIndex(0);
  }, []);

  // Slice an already-fetched array for AdvancedTable when the endpoint has no
  // skip/take of its own. Clamps pageIndex so deleting the last row of the
  // last page doesn't strand the table on an empty slice.
  const paginate = useCallback(
    <T,>(rows: T[]) => {
      const lastPage = Math.max(0, Math.ceil(rows.length / pageSize) - 1);
      const clamped = Math.min(pageIndex, lastPage);
      return {
        rows: rows.slice(clamped * pageSize, clamped * pageSize + pageSize),
        pageIndex: clamped,
        itemCount: rows.length,
      };
    },
    [pageIndex, pageSize],
  );

  return {
    pageIndex,
    setPageIndex,
    q,
    setQ,
    pageSize,
    setPageSize,
    skip: pageIndex * pageSize,
    take: pageSize,
    paginate,
  };
}
