import type { MouseEvent } from 'react'
import { useState, useCallback } from 'react'

import { getPlayerPlaylists } from 'requests/getPlayerPlaylists'

import { usePageParams } from 'hooks/usePageParams'

import {
  PlayerPlaylistOption,
  PlaylistOption,
  PlaylistTypes,
} from 'features/MatchPage/types'
import { defaultSettings } from 'features/MatchPopup/types'

export const useSelectedPlaylist = () => {
  const { profileId: matchId, sportType } = usePageParams()
  const [selectedPlaylist, setSelectedPlaylist] = useState<PlaylistOption>()

  const fetchPlayerEpisodes = useCallback((playlistOption: PlayerPlaylistOption) => (
    getPlayerPlaylists({
      matchId,
      playerId: playlistOption.id,
      settings: defaultSettings,
      sportType,
    })
  ), [matchId, sportType])

  const handlePlaylistClick = useCallback((playlist: PlaylistOption, e?: MouseEvent) => {
    e?.stopPropagation()
    if (playlist === selectedPlaylist) return

    if (playlist.type === PlaylistTypes.PLAYER) {
      fetchPlayerEpisodes(playlist).then((episodes) => {
        setSelectedPlaylist({
          ...playlist,
          episodes,
        })
      })
    } else {
      setSelectedPlaylist(playlist)
    }
  }, [fetchPlayerEpisodes, selectedPlaylist])

  return {
    handlePlaylistClick,
    selectedPlaylist,
    setSelectedPlaylist,
  }
}
