import { useEffect } from 'react'
import { useQueryClient } from 'react-query'

import findIndex from 'lodash/findIndex'
import isNil from 'lodash/isNil'

import { querieKeys } from 'config'

import type { MatchScore } from 'requests'
import { MatchStatuses } from 'requests'

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

import { Tabs } from './config'

export const useMatchSidePlaylists = () => {
  const {
    closePopup,
    profile: matchProfile,
    selectedTab,
    setSelectedTab,
  } = useMatchPageStore()
  const client = useQueryClient()

  const matchScore = client.getQueryData<MatchScore>(querieKeys.matchScore)

  const videoBounds = matchScore?.video_bounds || matchProfile?.video_bounds
  const matchStatus = matchScore?.c_match_calc_status || matchProfile?.c_match_calc_status

  const showTabs = Number(matchStatus) > MatchStatuses.Upcoming
    && findIndex(videoBounds, ({ h, s }) => h === '1' && !isNil(s)) !== -1

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

  return {
    onTabClick: setSelectedTab,
    selectedTab,
    showTabs,
  }
}
