import {
  useEffect,
  useState,
  useMemo,
} from 'react'

import type { UserFavorites } from 'requests'
import { modifyUserFavorites, getUserFavorites } from 'requests'
import { useLexicsStore } from 'features/LexicsStore'

import { normalizeUserFavorites } from '../helpers'

type Args = Parameters<typeof modifyUserFavorites>[0]

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

  useEffect(() => {
    getUserFavorites().then(setUserFavorites)
  }, [])

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

  const memoizedUserFavorites = useMemo(
    () => normalizeUserFavorites(userFavorites, suffix),
    [userFavorites, suffix],
  )

  return {
    addRemoveFavorite,
    userFavorites: memoizedUserFavorites,
  }
}
