import map from 'lodash/map'

import { MatchInfo, Param } from 'requests'

import {
  CellContainer,
  Container,
  Header,
  Row,
  StatItemTitle,
  Table,
  TableWrapper,
  TeamShortName,
} from 'features/MatchSidePlaylists/components/TeamsStatsTable/styled'
import { Cell } from 'features/MatchSidePlaylists/components/TeamsStatsTable/Cell'

import { TeamsStats } from 'features/MatchPage/store/hooks/useTeamsStats'

import { getStatItemById } from '../helpers'

type StatsTableProps = {
  firstClickableParam?: Param | null,
  isOpen?: boolean,
  profile: MatchInfo,
  teamsStats: TeamsStats,
}
export const StatsTable = ({
  firstClickableParam = null,
  isOpen = false,
  profile,
  teamsStats,
}: StatsTableProps) => {
  if (!profile) return null

  return (
    <Container>
      <TableWrapper isOpenTour={Boolean(isOpen)}>
        <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({
                matchProfile: profile,
                paramId: team1StatItem.param1.id,
                stats: teamsStats,
              })

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

                  <CellContainer>
                    <StatItemTitle t={team1StatItem.lexic} />
                  </CellContainer>

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