import { useState, useMemo } from 'react';

interface UsePaginationProps<T> {
  data: T[];
  defaultPageSize?: number;
}

export function usePagination<T>({ data, defaultPageSize = 20 }: UsePaginationProps<T>) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(defaultPageSize);

  const totalPages = Math.max(1, Math.ceil(data.length / pageSize));
  const safeCurrentPage = Math.min(page, totalPages);

  const paginatedData = useMemo(() => {
    const start = (safeCurrentPage - 1) * pageSize;
    return data.slice(start, start + pageSize);
  }, [data, safeCurrentPage, pageSize]);

  const handlePageChange = (newPage: number) => setPage(Math.max(1, Math.min(newPage, totalPages)));
  const handlePageSizeChange = (size: number) => { setPageSize(size); setPage(1); };

  return {
    paginatedData,
    page: safeCurrentPage,
    pageSize,
    totalPages,
    totalItems: data.length,
    setPage: handlePageChange,
    setPageSize: handlePageSizeChange,
  };
}
