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

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

interface Props<TQueryFnData>
  extends Omit<FlatListLayoutProps<TQueryFnData>, 'data'> {
  queryKey: QueryKey;
  queryFn: CursorQueryFn<TQueryFnData>;
  options?: CursorQueryOptions<TQueryFnData>;
}

function Cursor<TQueryFnData>(
  {
    renderItem,
    queryKey,
    queryFn,
    ListErrorComponent,
    filterable,
    onFilterText,
    options,
    ...props
  }: Props<TQueryFnData>,
  ref: ForwardedRef<FlatList<TQueryFnData>>,
) {
  const {data, isLoading, isFetchingNextPage, getNextPage, refresh} =
    useCursorInfinityQuery({queryKey, queryFn, options});

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

export default genericForwardRef(Cursor);
