import { useState, useEffect } from 'react'

import isEmpty from 'lodash/isEmpty'

import type { MatchPlaylists } from 'requests'
import { getMatchPlaylists } from 'requests'

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

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

export const useMatchPopup = () => {
  const [match, setMatch] = useState<MatchData>(null)
  const [matchPlaylists, setMatchPlaylists] = useState<MatchPlaylists | null>(null)
  const {
    closePopup,
    goBack,
    goToSettings,
    isOpen,
    openPopup,
    page,
  } = usePopupNavigation()

  const {
    episodeDuration,
    resetSelectedActions,
    selectedActions,
    selectedPlaylistFormat,
    setEpisodeDuration,
    setSelectedActions,
    setSelectedPlaylistFormat,
  } = useSettingsState(match?.sportType)

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

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

  useEffect(() => {
    if (selectedPlaylistFormat !== PlayerPlaylistFormats.SELECTED_ACTIONS) {
      resetSelectedActions()
    }
  }, [selectedPlaylistFormat, resetSelectedActions])

  useEffect(() => {
    const isSettingsPage = page === PopupPages.SETTINGS
    const actionsFormatSelected = (
      selectedPlaylistFormat === PlayerPlaylistFormats.SELECTED_ACTIONS
    )
    if (isSettingsPage && actionsFormatSelected) {
      fetchSportActions()
    }
  }, [
    selectedPlaylistFormat,
    match,
    page,
    fetchSportActions,
    resetSelectedActions,
  ])

  useEffect(() => {
    if (!match || !isOpen || page !== PopupPages.PLAYLIST) return

    getMatchPlaylists({
      matchId: match.id,
      // запрос с экшнами [1, 2, 3] временный
      selectedActions: isEmpty(selectedActions) ? [1, 2, 3] : selectedActions,
      sportType: match.sportType,
    }).then(setMatchPlaylists)
  }, [
    isOpen,
    match,
    page,
    selectedActions,
  ])

  return {
    actions,
    closePopup,
    episodeDuration,
    goBack,
    goToSettings,
    isOpen,
    match,
    matchPlaylists,
    onActionClick: setSelectedActions,
    onDurationChange: setEpisodeDuration,
    onFormatSelect: setSelectedPlaylistFormat,
    openPopup,
    page,
    selectedActions,
    selectedPlaylistFormat,
    setMatch,
  }
}
