import { useCallback, useState } from 'react'

import find from 'lodash/find'

import type { UserFavorites } from 'requests'
import { modifyUserFavorites, getUserFavorites } from 'requests'

import { useToggle } from 'hooks/useToggle'
import { ProfileTypes } from 'config'

type Args = Parameters<typeof modifyUserFavorites>[0]

export const useUserFavorites = () => {
  const [userFavorites, setUserFavorites] = useState<UserFavorites>([])

  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const fetchFavorites = useCallback(() => {
    getUserFavorites().then(setUserFavorites)
  }, [])

  const addRemoveFavorite = (args: Args) => {
    modifyUserFavorites(args).then(setUserFavorites, open)
  }

  const isInFavorites = (profileType: ProfileTypes, profileId: number) => (
    Boolean(find(userFavorites, { id: profileId, type: profileType }))
  )

  return {
    addRemoveFavorite,
    close,
    fetchFavorites,
    isInFavorites,
    isOpen,
    open,
    userFavorites,
  }
}
