import { useMemo } from 'react'

import { API_ROOT } from 'config'

import { readToken } from 'helpers/token'

import { usePageParams } from 'hooks/usePageParams'

import { useMatchPageStore } from 'features/MatchPage/store'

import { usePlayerProgressReporter } from './usePlayerProgressReporter'
import { useResumeUrlParam } from './useResumeUrlParam'
import { useChapters } from './useChapters'
import { usePlaylistLogger } from './usePlaylistLogger'

export const useLiveMatch = () => {
  const {
    handlePlaylistClick,
    profile,
    selectedPlaylist,
    setFullMatchPlaylistDuration,
  } = useMatchPageStore()
  const { profileId: matchId, sportType } = usePageParams()
  const resume = useResumeUrlParam()

  const fromStartIfStreamPaused = useMemo(
    () => (profile && !profile.live ? 0 : undefined),
    // deps намеренно оставляем пустым,
    // не нужно реагировать на изменение live когда пользователь смотрит матч
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  )

  const { chapters } = useChapters({
    profile,
    selectedPlaylist,
    url: `${API_ROOT}/video/stream/${sportType}/${matchId}.m3u8?access_token=${readToken()}`,
  })

  const {
    logPlaylistChange,
    onPlayingChange: notifyPlaylistLogger,
  } = usePlaylistLogger()

  const {
    onPlayerProgressChange,
    onPlayingChange: notifyProgressLogger,
  } = usePlayerProgressReporter()

  const onDurationChange = (duration: number) => {
    if (profile?.live && (!profile?.has_video || profile?.storage)) return
    setFullMatchPlaylistDuration(duration)
  }

  const onPlayingChange = (playing: boolean) => {
    notifyPlaylistLogger(playing)
    notifyProgressLogger(playing)
  }

  const onPlaylistSelect: typeof handlePlaylistClick = (playlist, e) => {
    if (selectedPlaylist) {
      logPlaylistChange(selectedPlaylist)
    }
    handlePlaylistClick(playlist, e)
  }
  return {
    chapters,
    onDurationChange,
    onPlayerProgressChange,
    onPlayingChange,
    onPlaylistSelect,
    resume: resume ?? fromStartIfStreamPaused,
    streamUrl: `${API_ROOT}/video/stream/${sportType}/${matchId}.m3u8`,
  }
}
