import { InfiniteData } from 'react-query';
import { QueryStatus } from 'react-query';

import { AxiosResponse } from 'axios';

import { PaginatedQueryStates } from 'src/hooks/usePaginatedQueryState';
import { Pagination, CursorPagination } from 'src/types/services';

export const getNextPage = (
  arrayLength: number,
  limit: number,
  pages: unknown[],
) => (arrayLength === limit ? pages.length + 1 : undefined);

export const getNextCursor = <T>(
  lastPage: AxiosResponse<CursorPagination<T>>,
) => lastPage?.data?.cursor;

export const getListLength = pages => pages[pages.length - 1].data.length;

export const getListItemsLength = pages =>
  pages[pages.length - 1].data.items.length;

type PaginationParamsBase = {
  page: number;
  limit: number;
  order?: string;
  orderBy?: string;
};

export type PaginationParams = PaginationParamsBase & {
  search?: string;
};

export type PaginationParamsWithQ = PaginationParamsBase & {
  q?: string;
};

export type PaginatedResponse<T> = {
  items: T[];
  count: number;
  totalPages: number;
  page: number;
  limit: number;
};

export const formatPagination = (pagination: PaginationParams) => ({
  ...pagination,
  page: pagination.page + 1,
});

export const DEFAULT_LIMIT = 10;

export const flatPages = <T>(
  infinite?: InfiniteData<
    AxiosResponse<CursorPagination<T[]> | Pagination<T[]>>
  >,
) => infinite?.pages?.flatMap(page => page.data.items) || [];

export const getPaginatedQueryState = <TData>(
  data: Pagination<TData> | undefined,
  status: QueryStatus,
  isOnline: boolean = true,
  isFiltered: boolean = false,
) => {
  const isEmpty = status === PaginatedQueryStates.SUCCESS && data?.count === 0;

  if (!isOnline && status === 'error')
    return PaginatedQueryStates.NETWORK_ERROR;
  if (isEmpty && isFiltered) return PaginatedQueryStates.EMPTY_SEARCH;
  if (isEmpty) return PaginatedQueryStates.EMPTY;

  return status as PaginatedQueryStates;
};
