import { useEffect } from 'react'

import { useToggle, useObjectState } from 'hooks'

import type { Settings } from 'features/MatchPopup'
import { useMatchPopupStore } from 'features/MatchPopup'
import { useMatchPageStore } from 'features/MatchPage/store'

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

const initPausedData = {
  activeChapterIndex: 0,
  activePlayer: 0 || 1,
  playedProgress: 0,
}

export type PausedData = typeof initPausedData

export const useFinishedMatch = () => {
  const [pausedData, setPausedData] = useObjectState<PausedData>(initPausedData)

  const { setChapters, setSettings } = useMatchPopupStore()
  const {
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
  } = useMatchPageStore()
  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,
    pausedData,
    playlists: matchPlaylists,
    selectedPlaylist,
    setEpisodesSettings,
    setPausedData,
  }
}
