import { useCallback } from 'react'

import find from 'lodash/find'

import { FavoritesActions } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import { useUserFavoritesStore } from 'features/UserFavorites/store'

export const useProfileCard = () => {
  const {
    addRemoveFavorite,
    setPlayerHighlight,
    userFavorites,
  } = useUserFavoritesStore()

  const {
    profileId,
    profileType,
    sportType,
  } = usePageParams()

  const isFavorite = Boolean(find(userFavorites, {
    id: profileId,
    sport: sportType,
    type: profileType,
  }))

  const toggleFavorites = useCallback(() => {
    const action = isFavorite
      ? FavoritesActions.REMOVE
      : FavoritesActions.ADD
    addRemoveFavorite({
      action,
      id: profileId,
      sport: sportType,
      type: profileType,
    })
  }, [
    isFavorite,
    addRemoveFavorite,
    profileId,
    profileType,
    sportType,
  ])

  return {
    isFavorite,
    profileId,
    profileType,
    setPlayerHighlight,
    sportType,
    toggleFavorites,
  }
}
