import {
  useState,
  useEffect,
} from 'react'

import isEmpty from 'lodash/isEmpty'

import { getMatchPlaylists } from 'requests'

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

import { useSettingsState } from './useSettingsState'
import { useSportActions } from './useSportActions'
import { usePopupNavigation } from './usePopupNavigation'

import type { MatchData } from '../../types'
import { PopupPages, PlayerPlaylistFormats } from '../../types'
import { usePlayerClickHandler } from './usePlayerClickHandler'
import { usePlaylistLexics } from './usePlaylistLexics'

export const useMatchPopup = () => {
  const [match, setMatch] = useState<MatchData>(null)

  const [matchPlaylists, setMatchPlaylists] = useState<Playlists | null>(null)
  const {
    closePopup,
    goBack,
    goTo,
    isOpen,
    openPopup,
    page,
  } = usePopupNavigation()

  const {
    setEpisodeDuration,
    setSelectedActions,
    setSelectedPlaylistFormat,
    settings,
  } = useSettingsState(match?.sportType)

  const {
    episodeDuration,
    selectedActions,
    selectedFormat: selectedPlaylistFormat,
  } = settings

  const { actions, fetchSportActions } = useSportActions(match?.sportType)

  const { fetchLexics } = usePlaylistLexics()

  useEffect(() => {
    if (selectedPlaylistFormat === PlayerPlaylistFormats.SELECTED_ACTIONS) {
      fetchSportActions()
    } else {
      setSelectedActions([])
    }
  }, [
    selectedPlaylistFormat,
    fetchSportActions,
    setSelectedActions,
  ])

  useEffect(() => {
    if (!isOpen) {
      setMatch(null)
      setMatchPlaylists(null)
    }
  }, [isOpen])

  useEffect(() => {
    const isPlaylistPage = page === PopupPages.PLAYLIST
    const actionsFormatSelected = (
      selectedPlaylistFormat === PlayerPlaylistFormats.SELECTED_ACTIONS
    )
    if (isPlaylistPage && actionsFormatSelected && isEmpty(selectedActions)) {
      setSelectedPlaylistFormat(PlayerPlaylistFormats.ALL_MATCH_TIME)
    }
  }, [
    selectedActions,
    selectedPlaylistFormat,
    page,
    setSelectedPlaylistFormat,
  ])

  useEffect(() => {
    if (!match) return

    getMatchPlaylists({
      matchId: match.id,
      selectedActions: [],
      sportType: match.sportType,
    }).then(fetchLexics)
      .then(buildPlaylists)
      .then(setMatchPlaylists)
  }, [match, fetchLexics])

  return {
    actions,
    closePopup,
    episodeDuration,
    goBack,
    goTo,
    isOpen,
    match,
    matchPlaylists,
    onActionClick: setSelectedActions,
    onDurationChange: setEpisodeDuration,
    onFormatSelect: setSelectedPlaylistFormat,
    openPopup,
    page,
    selectedActions,
    selectedPlaylistFormat,
    setMatch,
    ...usePlayerClickHandler({
      goTo,
      match,
      settings,
    }),
  }
}
