import { useToggle } from 'hooks/useToggle'

import type { Settings } from 'features/MatchPopup'
import { useMatchPopupStore } from 'features/MatchPopup'

import { usePlayerLogger } from './usePlayerLogger'
import { useEpisodes } from './useEpisodes'
import { useChapters } from './useChapters'

export const useFinishedMatch = () => {
  const {
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
    setSettings,
  } = useMatchPopupStore()
  const {
    close: closeSettingsPopup,
    isOpen: isSettingsPopupOpen,
    open: openSettingsPopup,
  } = useToggle()

  const { episodes } = useEpisodes()

  const { logPlaylistChange, onPlayingChange } = usePlayerLogger()

  const setEpisodesSettings = (newSettings: Settings) => {
    setSettings(newSettings)
    closeSettingsPopup()
  }

  const onPlaylistSelect: typeof handlePlaylistClick = (playlist, e) => {
    if (selectedPlaylist) {
      logPlaylistChange(selectedPlaylist)
    }
    handlePlaylistClick(playlist, e)
  }

  return {
    closeSettingsPopup,
    isSettingsPopupOpen,
    onPlayingChange,
    onPlaylistSelect,
    openSettingsPopup,
    playlists: matchPlaylists,
    selectedPlaylist,
    setEpisodesSettings,
    ...useChapters({
      episodes,
      selectedPlaylist,
    }),
  }
}
