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

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

interface Props<TData> extends Omit<FlatListLayoutProps<TData>, 'data'> {
  queryKey: QueryKey;
  queryFn: OffsetQueryFn<TData>;
}

function Offset<TData>(
  {queryKey, queryFn, renderItem, ...props}: Props<TData>,
  ref: ForwardedRef<FlatList<TData>>,
) {
  const {
    getNextPage,
    isFetching,
    isFetchingNextPage,
    isLoading,
    isRefreshing,
    refetch,
    data,
  } = useOffsetInfiniteQuery(queryKey, queryFn);

  return (
    <FlatListLayout
      {...props}
      ref={ref}
      data={data}
      renderItem={renderItem}
      showsVerticalScrollIndicator={false}
      onEndReached={getNextPage}
      isFetchingNextPage={isFetchingNextPage}
      isLoading={isLoading || isFetching}
      isRefreshing={isRefreshing}
      onRefresh={refetch}
    />
  );
}

export default genericForwardRef(Offset);
