import { useQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';

import {
  type PaginatedQueryStates,
  usePaginatedQueryState,
} from 'src/hooks/usePaginatedQueryState';
import { type RequestError, type RequestSuccess } from 'src/types/services';

import { SESSIONS_LIMIT, SESSIONS_STALE_TIME } from '../constants';
import { sessionsKeys } from '../queries';
import { getSessions } from '../services';
import { type GetSessionsParams } from '../types';

import { useSessionsFilters } from './useSessionsFilters';

export type SessionsPaginatedQueryStates = PaginatedQueryStates;

export type TSuccess = RequestSuccess<typeof getSessions>;
export type TError = RequestError;
export type TData = TSuccess['data'];

export const useGetSessions = () => {
  const { search, tab } = useSessionsFilters();
  const debouncedSearch = useDebounce(search);

  const params: GetSessionsParams = {
    q: debouncedSearch || undefined,
    status: tab || undefined,
    limit: SESSIONS_LIMIT,
    page: 1,
  };

  const { data, ...query } = useQuery<TSuccess, TError, TData>({
    queryKey: sessionsKeys.sessions.list(params),
    queryFn: () => getSessions(params),
    select: response => response.data,
    keepPreviousData: true,
    staleTime: SESSIONS_STALE_TIME,
  });

  const sessions = data?.items ?? [];

  const isFiltered = search?.length > 0;

  const queryState = usePaginatedQueryState(data, query.status, isFiltered);

  return {
    ...query,
    ...queryState,
    sessions,
  };
};
