import React, {ForwardedRef} from 'react';
import {QueryKey} from 'react-query';
import {FlatList} from 'react-native-gesture-handler';
import {useInfiniteQuery} from '@hooks/queries/useInfiniteQuery';
import {FlatListLayoutProps} from '@components/InfinityScrollFlatList/interfaces';
import {PageLimitQueryFn} from '@config/api';
import {QueryOptions} from '@interfaces/queries';
import {genericForwardRef} from '@components/InfinityScrollFlatList/utils';

import {FlatListLayout} from '../FlatListLayout';

interface Props<TQueryFnData>
  extends Omit<FlatListLayoutProps<TQueryFnData>, 'data'> {
  queryKey: QueryKey;
  queryFn: PageLimitQueryFn<TQueryFnData>;
  queryOptions?: QueryOptions<TQueryFnData>;
}

function PageLimit<TQueryFnData>(
  {
    renderItem,
    queryKey,
    queryFn,
    ListErrorComponent,
    queryOptions,
    animated,
    ...props
  }: Props<TQueryFnData>,
  ref: ForwardedRef<FlatList<TQueryFnData>>,
) {
  const {
    data,
    isLoading,
    isError,
    isRefreshing,
    isFetchingNextPage,
    getNextPage,
    refresh,
  } = useInfiniteQuery(queryKey, queryFn, queryOptions);

  return (
    <FlatListLayout
      {...props}
      ref={ref}
      data={data}
      renderItem={renderItem}
      onEndReached={getNextPage}
      isFetchingNextPage={isFetchingNextPage}
      isLoading={isLoading}
      isRefreshing={isRefreshing}
      onRefresh={refresh}
      isError={isError}
      ListErrorComponent={ListErrorComponent}
      animated={animated}
    />
  );
}

export default genericForwardRef(PageLimit);
