import { useState } from 'react'

import map from 'lodash/map'

import type { UserFavorites } from 'requests/getUserSportFavs'
import { T9n } from 'features/T9n'
import { SportIcon } from 'features/SportIcon'
import { useLexicsStore } from 'features/LexicsStore'
import { ProfileLink } from 'features/ProfileLink'
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,
  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 (
            <Item key={item.id}>
              <SportItemLogoWrapper>
                <ProfileLink
                  id={item.id}
                  sportType={item.sport}
                  profileType={item.type}
                >
                  <UserSportFavImgWrapper
                    id={item.id}
                    altNameObj={item}
                    sportType={item.sport}
                    profileType={item.type}
                  />
                </ProfileLink>
              </SportItemLogoWrapper>

              <EmptyDiv>
                <Name>{name}</Name>
                <CountryAndTeamInfo>
                  <SportIcon sport={item.sport} />
                  <Flag src={`https://instatscout.com/images/flags/48/${item.info.country?.id}.png`} />
                  <EmptySpan>{countryOrTeam}</EmptySpan>
                </CountryAndTeamInfo>
              </EmptyDiv>
            </Item>
          )
        })}
      </ContentWrapper>
    </BlockWrapper>
  )
}
