import map from 'lodash/map'

import { useMatchPageStore } from 'features/MatchPage/store'
import { useLexicsStore } from 'features/LexicsStore'
import { Loader } from 'features/Loader'
import { defaultTheme } from 'features/Theme/config'

import { useTeamsStatsTable } from './hooks'
import { Cell } from './Cell'
import {
  Container,
  TableWrapper,
  Table,
  Header,
  Row,
  CellContainer,
  TeamShortName,
  StatItemTitle,
} from './styled'

export const TeamsStatsTable = () => {
  const {
    isTeamsStatsFetching,
    profile,
    teamsStats,
  } = useMatchPageStore()

  const { getStatItemById } = useTeamsStatsTable()

  const { shortSuffix } = useLexicsStore()

  if (!profile) return null

  if (isTeamsStatsFetching) {
    return (
      <Loader color={defaultTheme.colors.white} />
    )
  }

  return (
    <Container>
      <TableWrapper>
        <Table role='marquee' aria-live='off'>
          <Header>
            <Row>
              <CellContainer as='th'>
                <TeamShortName
                  nameObj={profile.team1}
                  prefix='abbrev_'
                />
              </CellContainer>
              <CellContainer as='th' />
              <CellContainer as='th'>
                <TeamShortName
                  nameObj={profile.team2}
                  prefix='abbrev_'
                />
              </CellContainer>
            </Row>
          </Header>

          <tbody>
            {map(teamsStats[profile.team1.id], (team1StatItem) => {
              const team2StatItem = getStatItemById(team1StatItem.param1.id)
              const statItemTitle = team1StatItem[`name_${shortSuffix}`]

              return (
                <Row key={team1StatItem.param1.id}>
                  <Cell
                    teamStatItem={team1StatItem}
                    teamId={profile.team1.id}
                  />

                  <CellContainer>
                    <StatItemTitle>{statItemTitle}</StatItemTitle>
                  </CellContainer>

                  <Cell
                    teamStatItem={team2StatItem}
                    teamId={profile.team2.id}
                  />
                </Row>
              )
            })}
          </tbody>
        </Table>
      </TableWrapper>
    </Container>
  )
}
