import React, {ForwardedRef} from 'react';
import {QueryKey} from 'react-query';
import {FlatList} from 'react-native-gesture-handler';
import {CursorQueryFn, OffsetQueryFn, PageLimitQueryFn} from '@config/api';
import {CursorQueryOptions, QueryOptions} from '@interfaces/queries';

import PageLimit from './components/PageLimit';
import Offset from './components/Offset';
import {FlatListLayoutProps} from './interfaces';
import Cursor from './components/Cursor';
import {genericForwardRef} from './utils';

interface Props<TQueryFnData>
  extends Omit<FlatListLayoutProps<TQueryFnData>, 'data'> {
  queryKey: QueryKey;
  queryFn:
    | PageLimitQueryFn<TQueryFnData>
    | OffsetQueryFn<TQueryFnData>
    | CursorQueryFn<TQueryFnData>;
  queryOptions?: QueryOptions<TQueryFnData>;
  variant?: 'default' | 'offset' | 'cursor';
}

function InfinityScrollFlatListForwardedRef<TQueryFnData>(
  {variant = 'default', queryFn, ...props}: Props<TQueryFnData>,
  ref: ForwardedRef<FlatList<TQueryFnData>>,
) {
  const {queryOptions} = props;
  switch (variant) {
    case 'default':
      return (
        <PageLimit
          ref={ref}
          queryFn={queryFn as PageLimitQueryFn<TQueryFnData>}
          {...props}
        />
      );
    case 'offset':
      return (
        <Offset
          ref={ref}
          queryFn={queryFn as OffsetQueryFn<TQueryFnData>}
          {...props}
        />
      );
    case 'cursor':
      return (
        <Cursor
          ref={ref}
          queryFn={queryFn as CursorQueryFn<TQueryFnData>}
          options={queryOptions as CursorQueryOptions<TQueryFnData>}
          {...props}
        />
      );
    default:
      return null;
  }
}

export const InfinityScrollFlatList = genericForwardRef(
  InfinityScrollFlatListForwardedRef,
);

export * from './interfaces';
