import React, { useCallback } from 'react';
import { Box, Pagination, PaginationProps } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { CollectionStateProps } from './collectionStateProps';
import { FiltersMap } from '@wix/bex-core';
import { useScrollableContentContext } from '../providers';

export interface CollectionPaginationProps<T, F extends FiltersMap>
  extends CollectionStateProps<T, F>,
    Partial<PaginationProps> {}

export const CollectionPagination = observer(function PaginationTable<
  T,
  F extends FiltersMap,
>({ state, ...rest }: CollectionPaginationProps<T, F>) {
  const {
    result: { status },
    totalPages,
    query: { pagination },
  } = state;

  const { scrollableContentRef } = useScrollableContentContext();
  const showPagination = totalPages > 0 && !status.isLoading;

  const onPageChange = useCallback(async ({ page }: { page: number }) => {
    scrollableContentRef?.current?.scrollTo({ top: 0 });
    await state.clearAndMoveToPage(page);
  }, []);

  return (
    <Box align="center" padding="SP8">
      {showPagination && (
        <Pagination
          totalPages={totalPages}
          currentPage={pagination.page}
          onChange={onPageChange}
          {...rest}
        />
      )}
    </Box>
  );
});
