import { useEffect, useMemo } from 'react'

import reduce from 'lodash/reduce'
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,
    tournamentData,
  } = useMatchPageStore()

  const playListFilter = useMemo(() => reduce(
    playlists.match,
    (acc, item) => {
      let result = acc
      if (item.duration) result++
      return result
    },
    0,
  ), [playlists.match])

  const isWatchTabVisible = useMemo(() => (
    playListFilter > 1 || tournamentData.matchDates.length > 1
  ), [playListFilter, tournamentData.matchDates.length])

  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,
    playListFilter,
    selectedTab,
  }
}
