import { isMobileDevice } from 'config/userAgent'

import { getTeamAbbr } from 'helpers'

import { Tooltip } from 'features/Tooltip'
import { T9n } from 'features/T9n'
import { useMatchPageStore } from 'features/MatchPage/store'
import { Name } from 'features/Name'

import { Tabs } from './config'
import { useTabStats } from './hooks'
import { PlayersTable } from '../PlayersTable'
import { TeamsStatsTable } from '../TeamsStatsTable'

import {
  Container,
  Header,
  TabList,
  Tab,
  Switch,
  SwitchTitle,
  SwitchButton,
} from './styled'

const tabPanes = {
  [Tabs.TEAMS]: TeamsStatsTable,
  [Tabs.TEAM1]: PlayersTable,
  [Tabs.TEAM2]: PlayersTable,
}

export const TabStats = () => {
  const {
    isFinalStatsType,
    isVisibleTeam1PlayersTab,
    isVisibleTeam2PlayersTab,
    isVisibleTeamsTab,
    selectedTab,
    setSelectedTab,
    switchTitleLexic,
    toggleStatsType,
    tooltipLexic,
  } = useTabStats()
  const { profile: matchProfile } = useMatchPageStore()

  const TabPane = tabPanes[selectedTab]

  if (!matchProfile) return null

  const { team1, team2 } = matchProfile

  return (
    <Container>
      <Header>
        <TabList>
          {isVisibleTeamsTab && (
            <Tab
              aria-pressed={selectedTab === Tabs.TEAMS}
              onClick={() => setSelectedTab(Tabs.TEAMS)}
            >
              <T9n t='team' />
            </Tab>
          )}
          {isVisibleTeam1PlayersTab && (
            <Tab
              aria-pressed={selectedTab === Tabs.TEAM1}
              onClick={() => setSelectedTab(Tabs.TEAM1)}
            >
              <Name nameObj={{
                name_eng: team1.abbrev_eng || getTeamAbbr(team1.name_eng),
                name_rus: team1.abbrev_rus || getTeamAbbr(team1.name_rus),
              }}
              />
            </Tab>
          )}
          {isVisibleTeam2PlayersTab && (
            <Tab
              aria-pressed={selectedTab === Tabs.TEAM2}
              onClick={() => setSelectedTab(Tabs.TEAM2)}
            >
              <Name nameObj={{
                name_eng: team2.abbrev_eng || getTeamAbbr(team2.name_eng),
                name_rus: team2.abbrev_rus || getTeamAbbr(team2.name_rus),
              }}
              />
            </Tab>
          )}
        </TabList>
        <Switch>
          <SwitchTitle t={switchTitleLexic} />
          <SwitchButton
            isFinalStatsType={isFinalStatsType}
            onClick={toggleStatsType}
          >
            {!isMobileDevice && <Tooltip lexic={tooltipLexic} />}
          </SwitchButton>
        </Switch>
      </Header>
      <TabPane
        teamId={selectedTab === Tabs.TEAM1 ? team1.id : team2.id}
      />
    </Container>
  )
}
