import {
  useState,
  useCallback,
  useEffect,
} from 'react'

import isEmpty from 'lodash/isEmpty'

import type { SportTypes } from 'config/sportTypes'

import { MatchInfo } from 'requests/getMatchInfo'
import { getMatchPlaylists } from 'requests/getMatchPlaylists'

import { usePageParams } from 'hooks/usePageParams'

import type { Playlists } from 'features/MatchPage/types'
import { buildPlaylists, FULL_GAME_KEY } from 'features/MatchPage/helpers/buildPlaylists'

import { usePlaylistLexics } from './usePlaylistLexics'
import { useSelectedPlaylist } from './useSelectedPlaylist'

type ArgsFetchMatchPlaylists = {
  fullMatchDuration: number,
  id: number,
  sportType: SportTypes,
}

const initialPlaylists = buildPlaylists(null)

export const useMatchPlaylists = (profile: MatchInfo) => {
  const [matchPlaylists, setMatchPlaylists] = useState<Playlists>(initialPlaylists)

  const { fetchLexics } = usePlaylistLexics()
  const { profileId } = usePageParams()
  const {
    handlePlaylistClick,
    selectedPlaylist,
    setSelectedPlaylist,
  } = useSelectedPlaylist()

  const setInitialSeletedPlaylist = useCallback((playlists: Playlists) => {
    setSelectedPlaylist((playlist) => {
      if ((!playlist && !isEmpty(playlists.match))
          || (profile?.live && selectedPlaylist?.id === FULL_GAME_KEY)) {
        return playlists.match[0]
      }
      return playlist
    })
    return playlists
  }, [
    profile,
    setSelectedPlaylist,
    selectedPlaylist?.id,
  ])

  const fetchMatchPlaylists = useCallback(({
    fullMatchDuration,
    id,
    sportType,
  }: ArgsFetchMatchPlaylists) => {
    getMatchPlaylists({
      fullMatchDuration,
      matchId: id,
      selectedActions: [],
      sportType,
    }).then(fetchLexics)
      .then(buildPlaylists)
      .then(setInitialSeletedPlaylist)
      .then(setMatchPlaylists)
  }, [fetchLexics, setInitialSeletedPlaylist])

  useEffect(() => {
    if (selectedPlaylist?.id !== FULL_GAME_KEY) return
    setSelectedPlaylist(matchPlaylists?.match[0])
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    matchPlaylists?.match,
    profileId,
    setSelectedPlaylist,
  ])

  /**
   * API не выдает длительность Полного матча
   * Здесь получаем его из самого видео
   * и обновляем длительность плейлиста Полный матч
   */
  const setFullMatchPlaylistDuration = (duration: number) => {
    const playlists = [...matchPlaylists.match]
    if (!playlists[0]) return

    playlists[0].duration = duration
    setMatchPlaylists({
      ...matchPlaylists,
      match: playlists,
    })

    if (selectedPlaylist) {
      setSelectedPlaylist({ ...selectedPlaylist })
    }
  }

  return {
    fetchMatchPlaylists,
    handlePlaylistClick,
    matchPlaylists,
    selectedPlaylist,
    setFullMatchPlaylistDuration,
    setSelectedPlaylist,
  }
}
