import { useEffect, useState } from 'react'

import isEmpty from 'lodash/isEmpty'

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,
    setStatsType,
    statsType,
    teamsStats,
  } = useMatchPageStore()

  const isFinalStatsType = statsType === StatsType.FINAL_STATS

  const switchTitleLexic = isFinalStatsType ? 'final_stats' : 'current_stats'
  const tooltipLexic = 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),
  )

  const toggleStatsType = () => {
    const newStatsType = isFinalStatsType ? StatsType.CURRENT_STATS : StatsType.FINAL_STATS

    setStatsType(newStatsType)
  }

  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,
    isVisibleTeam1PlayersTab,
    isVisibleTeam2PlayersTab,
    isVisibleTeamsTab,
    selectedTab,
    setSelectedTab,
    switchTitleLexic,
    toggleStatsType,
    tooltipLexic,
  }
}
