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

import reduce from 'lodash/reduce'

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

import { Tabs } from './config'

export const useMatchSidePlaylists = () => {
  const {
    closePopup,
    events,
    matchPlaylists: playlists,
    tournamentData,
  } = useMatchPageStore()
  const [selectedTab, setSelectedTab] = useState<Tabs>(Tabs.WATCH)
  const isWatchTabVisible = useMemo(() => {
    const playListFilter = reduce(
      playlists.match,
      (acc, item) => {
        let result = acc
        if (item.duration) result++
        return result
      },
      0,
    )
    return playListFilter > 1
  }, [playlists])

  const isEventTabVisible = useMemo(() => (
    events.length > 0
  ), [events])

  const isVideoTabVisible = useMemo(() => (
    tournamentData.matches.length > 1
  ), [tournamentData])

  useEffect(() => {
    switch (true) {
      case isWatchTabVisible:
        setSelectedTab(Tabs.WATCH)
        break
      case isEventTabVisible:
        setSelectedTab(Tabs.EVENTS)
        break
      case isVideoTabVisible:
        setSelectedTab(Tabs.VIDEO)
        break
    }
  }, [isEventTabVisible, isVideoTabVisible, isWatchTabVisible])

  useEffect(() => {
    if (selectedTab !== Tabs.EVENTS) closePopup()
  }, [selectedTab, closePopup])

  return {
    isEventTabVisible,
    isVideoTabVisible,
    isWatchTabVisible,
    onTabClick: setSelectedTab,
    selectedTab,
  }
}
