import { Fragment } from 'react'

import map from 'lodash/map'

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

import { useTeamsStatsTable } from './hooks'
import {
  Container,
  Row,
  TeamShortName,
  ParamValueContainer,
  ParamValue,
  StatItemTitle,
  Divider,
} from './styled'

export const TeamsStatsTable = () => {
  const { profile, teamsStats } = useMatchPageStore()
  const {
    getDisplayedValue,
    getStatItemById,
    isClickable,
  } = useTeamsStatsTable()
  const { lang } = useLexicsStore()

  if (!profile) return null

  return (
    <Container>
      <Row>
        <TeamShortName
          nameObj={profile.team1}
          prefix='abbrev_'
        />
        <TeamShortName
          nameObj={profile.team2}
          prefix='abbrev_'
        />
      </Row>

      {map(teamsStats[profile.team1.id], (team1StatItem) => {
        const team2StatItem = getStatItemById(team1StatItem.param1.id)
        const statItemTitle = team1StatItem[`name_${lang === 'ru' ? 'ru' : 'en'}`]

        return (
          <Row key={team1StatItem.param1.id}>
            <ParamValueContainer>
              <ParamValue
                clickable={isClickable(team1StatItem.param1)}
              >
                {getDisplayedValue(team1StatItem.param1.val)}
              </ParamValue>
              {team1StatItem.param2 && (
                <Fragment>
                  <Divider>/</Divider>
                  <ParamValue
                    clickable={isClickable(team1StatItem.param2)}
                  >
                    {getDisplayedValue(team1StatItem.param2.val)}
                  </ParamValue>
                </Fragment>
              )}
            </ParamValueContainer>

            <StatItemTitle>{statItemTitle}</StatItemTitle>

            {team2StatItem && (
              <ParamValueContainer>
                <ParamValue
                  clickable={isClickable(team2StatItem.param1)}
                >
                  {getDisplayedValue(team2StatItem.param1.val)}
                </ParamValue>
                {team2StatItem.param2 && (
                  <Fragment>
                    <Divider>/</Divider>
                    <ParamValue
                      clickable={isClickable(team2StatItem.param2)}
                    >
                      {getDisplayedValue(team2StatItem.param2.val)}
                    </ParamValue>
                  </Fragment>
                )}
              </ParamValueContainer>
            )}
          </Row>
        )
      })}
    </Container>
  )
}
