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

import isEmpty from 'lodash/isEmpty'

import type { Episodes } from 'requests'
import { getPlayerPlaylists } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import { PlaylistOption, PlaylistTypes } from 'features/MatchPage/types'
import { useMatchPageStore } from 'features/MatchPage/store'

import {
  defaultSettings,
  Settings,
  useMatchPopupStore,
} from 'features/MatchPopup'

export const useEpisodes = () => {
  const { settings } = useMatchPopupStore()
  const {
    handlePlaylistClick,
    matchPlaylists: playlists,
    selectedPlaylist,
  } = useMatchPageStore()
  const [episodes, setEpisodes] = useState<Episodes>([])
  const { profileId: matchId, sportType } = usePageParams()

  const fetchEpisodes = useCallback((
    playlistOption: PlaylistOption,
    popupSettings: Settings = defaultSettings,
  ) => {
    if (playlistOption.type === PlaylistTypes.PLAYER) {
      getPlayerPlaylists({
        matchId,
        playerId: playlistOption.id,
        settings: popupSettings,
        sportType,
      }).then(setEpisodes)
    } else if (playlistOption.type === PlaylistTypes.MATCH
       || playlistOption.type === PlaylistTypes.EVENT) {
      setEpisodes(playlistOption.episodes)
    }
  }, [matchId, sportType])

  useEffect(() => {
    if (!selectedPlaylist && playlists && !isEmpty(playlists.match)) {
      handlePlaylistClick(playlists.match[0])
    }
  }, [
    selectedPlaylist,
    playlists,
    handlePlaylistClick,
  ])

  useEffect(() => {
    if (selectedPlaylist) {
      fetchEpisodes(selectedPlaylist, settings)
    }
  }, [
    settings,
    selectedPlaylist,
    fetchEpisodes,
  ])

  return { episodes }
}
