import { useState } from 'react'

import map from 'lodash/map'

import { URL_AWS } from 'config'

import type { UserFavorites } from 'requests/getUserSportFavs'
import { T9n } from 'features/T9n'
import { SportIcon } from 'components/SportIcon/SportIcon'
import { useLexicsStore } from 'features/LexicsStore'
import { UserSportFavImgWrapper } from 'features/UserFavorites/styled'
import { Flag } from 'features/ItemsList/styled'

import { getFavoriteItemNames } from './helpers'
import {
  BlockWrapper,
  ContentWrapper,
  EmptyDiv,
  EmptySpan,
  Item,
  CountryAndTeamInfo,
  SportItemLogoWrapper,
  Arrows,
  TitleWrapper,
  FavLink,
  Name,
} from './styled'

type Props = {
  groupBlock: {
    items: UserFavorites,
    typeLexic: string,
  },
}

export const GroupBlock = ({ groupBlock }: Props) => {
  const [activeItems, setActiveItems] = useState(true)
  const { items, typeLexic } = groupBlock
  const { suffix } = useLexicsStore()

  return (
    <BlockWrapper>
      <TitleWrapper>
        <T9n t={typeLexic} />
        <Arrows
          onClick={() => setActiveItems(!activeItems)}
          active={activeItems}
        />
      </TitleWrapper>
      <ContentWrapper>
        {activeItems && map(items, (item) => {
          const favoriteItemNames = getFavoriteItemNames(item, suffix)
          const { countryOrTeam, name } = favoriteItemNames

          return (
            <FavLink
              id={item.id}
              sportType={item.sport}
              profileType={item.type}
            >
              <Item key={item.id}>
                <SportItemLogoWrapper>
                  <UserSportFavImgWrapper
                    id={item.id}
                    altNameObj={item}
                    sportType={item.sport}
                    profileType={item.type}
                  />
                </SportItemLogoWrapper>
                <EmptyDiv>
                  <Name>{name}</Name>
                  <CountryAndTeamInfo>
                    <SportIcon sport={item.sport} size={10} />
                    <Flag src={`${URL_AWS}/media/flags/${item.info.country?.id}.png`} />
                    <EmptySpan>{countryOrTeam}</EmptySpan>
                  </CountryAndTeamInfo>
                </EmptyDiv>
              </Item>
            </FavLink>
          )
        })}
      </ContentWrapper>
    </BlockWrapper>
  )
}
