import React, { MutableRefObject } from 'react';
import { LoaderProps } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { CollectionStateProps } from '../collectionStateProps';
import { FiltersMap } from '@wix/bex-core';

export interface InfiniteScrollLoaderProps<T, F extends FiltersMap>
  extends CollectionStateProps<T, F>,
    Partial<LoaderProps> {
  targetRef: MutableRefObject<HTMLElement | null | undefined>;
  children: JSX.Element;
}

export const InfiniteScrollLoaderBase = observer(
  function InfiniteScrollLoaderBase<T, F extends FiltersMap>({
    state,
    targetRef,
    children,
  }: InfiniteScrollLoaderProps<T, F>) {
    const { fetchedLastPage, showRefreshLoader, showErrorState } = state;
    return (
      <>
        <div
          ref={(el) => {
            targetRef.current = el as HTMLElement | null;
          }}
        />
        {!fetchedLastPage && !showRefreshLoader && !showErrorState && children}
      </>
    );
  },
);
