import { useEffect } from 'react'

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,
    setChapters,
    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)
  }
  const { chapters } = useChapters({ episodes, selectedPlaylist })

  useEffect(() => {
    setChapters(chapters)
  }, [chapters, setChapters])

  return {
    chapters,
    closeSettingsPopup,
    isSettingsPopupOpen,
    onPlayingChange,
    onPlaylistSelect,
    openSettingsPopup,
    playlists: matchPlaylists,
    selectedPlaylist,
    setEpisodesSettings,
  }
}
