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,
  } = 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])

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

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

  return {
    isEventTabVisible,
    isStatsTabVisible: true,
    isWatchTabVisible,
    onTabClick: setSelectedTab,
    selectedTab,
  }
}
