import { useQuery } from 'react-query';

import { type AxiosResponse } from 'axios';
import { minutesToMilliseconds } from 'date-fns';
import { sample } from 'lodash-es';

import { queryClient } from 'src/config/react-query';
import useAuth from 'src/contexts/JWTContext';
import * as iconsService from 'src/services/iconsService';
import {
  type IconInterface,
  IconType,
  type ImageIconOption,
} from 'src/types/icons';
import { removeURLParams } from 'src/utils/filesUtils';

export const getIcons = () =>
  (queryClient.getQueryData('icons') as AxiosResponse<ImageIconOption[]>)?.data;

// we need 'icons' to have initial data so we can get a random icon on each formatDefaultIcon() call
// we need 'icons' to be refetched every 5 mins so the URLs don't expire
export const useIconsRefetch = () => {
  const { instance } = useAuth();

  useQuery('icons', iconsService.getIcons, {
    enabled: !!instance,
    refetchInterval: minutesToMilliseconds(5),
  });

  return !instance || getIcons();
};

export const formatDefaultIcon = (icon?: IconInterface) => {
  const icons = getIcons();

  return {
    type: icon?.type || IconType.IMAGE,
    value: icon?.value || sample(icons)?.source || '',
  };
};

export const formatOutgoingIcon = (icon: IconInterface) => ({
  type: icon.type,
  value:
    icon.type === IconType.IMAGE ? removeURLParams(icon.value) : icon.value,
});
