import { useCallback, useState } from 'react'

import find from 'lodash/find'

import type { ObjectWithName } from 'features/Name'

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

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

type ProfileType = {
  profile: ObjectWithName & {
    additionalInfo: ObjectWithName & {
      id: number,
      tournamentId?: number,
    },
    id: number,
  },
  sportType: number,
}

type Args = Parameters<typeof modifyUserFavorites>[0]

export const useUserFavorites = () => {
  const [userFavorites, setUserFavorites] = useState<UserFavorites>([])
  const [playerHighlight, setPlayerHighlight] = useState<ProfileType>({} as ProfileType)

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

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

  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,
    playerHighlight,
    setPlayerHighlight,
    userFavorites,
  }
}
