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

import reduce from 'lodash/reduce'

import { Playlists, TournamentData } from 'features/MatchPage/types'

import type { Events } from 'requests'

import { Tabs } from './config'

export type Props = {
  events: Events,
  playlists: Playlists,
  tournamentData: TournamentData,
}

export const useMatchSidePlaylists = (props: Props) => {
  const {
    events,
    playlists,
    tournamentData,
  } = props

  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])

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