import { useEffect, useMemo } from 'react'

import isEmpty from 'lodash/isEmpty'
import compact from 'lodash/compact'

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

import { Tabs } from './config'

export const useMatchSidePlaylists = () => {
  const {
    closePopup,
    events,
    isEmptyPlayersStats,
    matchPlaylists: playlists,
    profile: matchProfile,
    selectedTab,
    setSelectedTab,
    teamsStats,
  } = useMatchPageStore()

  const isWatchTabVisible = true

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

  const isPlayersTabVisible = useMemo(() => (
    !isEmpty(playlists.players.team1)
  ), [playlists.players.team1])

  const isStatsTabVisible = useMemo(() => (
    !isEmpty(teamsStats)
      || (matchProfile?.team1.id && !isEmptyPlayersStats(matchProfile.team1.id))
      || (matchProfile?.team2.id && !isEmptyPlayersStats(matchProfile.team2.id))
  ), [
    isEmptyPlayersStats,
    matchProfile?.team1.id,
    matchProfile?.team2.id,
    teamsStats,
  ])

  const hasLessThanFourTabs = compact([
    isWatchTabVisible,
    isEventTabVisible,
    isPlayersTabVisible,
    isStatsTabVisible,
  ]).length < 4

  useEffect(() => {
    switch (true) {
      case isWatchTabVisible:
        setSelectedTab(Tabs.WATCH)
        break
      case isEventTabVisible:
        setSelectedTab(Tabs.EVENTS)
        break
      case isPlayersTabVisible:
        setSelectedTab(Tabs.PLAYERS)
        break
      case isStatsTabVisible:
        setSelectedTab(Tabs.STATS)
        break
    }
  }, [
    isEventTabVisible,
    isPlayersTabVisible,
    isStatsTabVisible,
    isWatchTabVisible,
    setSelectedTab,
  ])

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

  return {
    hasLessThanFourTabs,
    isEventTabVisible,
    isPlayersTabVisible,
    isStatsTabVisible,
    isWatchTabVisible,
    onTabClick: setSelectedTab,
    selectedTab,
  }
}
