import { useEffect, useState } from 'react'

import isEmpty from 'lodash/isEmpty'

import { useTooltip } from 'hooks'

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

import { StatsType, Tabs } from './config'

export const useTabStats = () => {
  const [selectedTab, setSelectedTab] = useState<Tabs>(Tabs.TEAMS)

  const {
    isEmptyPlayersStats,
    profile: matchProfile,
    statsType,
    teamsStats,
    toggleStatsType,
  } = useMatchPageStore()

  const {
    isTooltipShown,
    onMouseLeave,
    onMouseOver,
    tooltipStyle,
    tooltipText,
  } = useTooltip()

  const isFinalStatsType = statsType === StatsType.FINAL_STATS

  const switchTitleLexic = isFinalStatsType ? 'final_stats' : 'current_stats'
  const switchButtonTooltipLexic = isFinalStatsType ? 'display_all_stats' : 'display_stats_according_to_video'

  const isVisibleTeamsTab = !isEmpty(teamsStats)
  const isVisibleTeam1PlayersTab = Boolean(
    matchProfile && !isEmptyPlayersStats(matchProfile.team1.id),
  )
  const isVisibleTeam2PlayersTab = Boolean(
    matchProfile && !isEmptyPlayersStats(matchProfile.team2.id),
  )

  useEffect(() => {
    switch (true) {
      case isVisibleTeamsTab:
        setSelectedTab(Tabs.TEAMS)
        break

      case isVisibleTeam1PlayersTab:
        setSelectedTab(Tabs.TEAM1)
        break

      case isVisibleTeam2PlayersTab:
        setSelectedTab(Tabs.TEAM2)
        break

      default:
    }
  }, [isVisibleTeam1PlayersTab, isVisibleTeam2PlayersTab, isVisibleTeamsTab])

  return {
    isFinalStatsType,
    isTooltipShown,
    isVisibleTeam1PlayersTab,
    isVisibleTeam2PlayersTab,
    isVisibleTeamsTab,
    onMouseLeave,
    onMouseOver,
    selectedTab,
    setSelectedTab,
    switchButtonTooltipLexic,
    switchTitleLexic,
    toggleStatsType,
    tooltipStyle,
    tooltipText,
  }
}
