import {
  useState,
  useCallback,
} from 'react'

import isEmpty from 'lodash/isEmpty'

import type { SportTypes } from 'config/sportTypes'

import { getMatchPlaylists } from 'requests/getMatchPlaylists'

import type { Playlists } from 'features/MatchPage/types'
import { buildPlaylists } 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 = () => {
  const [matchPlaylists, setMatchPlaylists] = useState<Playlists>(initialPlaylists)

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

  const setInitialSeletedPlaylist = useCallback((playlists: Playlists) => {
    setSelectedPlaylist((playlist) => {
      if (!playlist && !isEmpty(playlists.match)) {
        return playlists.match[0]
      }
      return playlist
    })
    return playlists
  }, [setSelectedPlaylist])

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

  /**
   * 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,
  }
}
