import { useState } from 'react'

import map from 'lodash/map'

import { ProfileTypes } from 'config'

import type { MatchInfo } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import type {
  PlayerPlaylistOptions,
  PlayerPlaylistOption,
  PlaylistOption,
} from 'features/MatchPage/types'

import { Name } from 'features/Name'

import { isEqual } from '../../helpers'

import {
  Wrapper,
  List,
  PlayersItem,
  PlayerAvatar,
  Tabs,
  Tab,
  PlayerNum,
  PlayButton,
} from './styled'

enum Teams {
  TEAM1 = 'team1',
  TEAM2 = 'team2',
}

type Props = {
  onSelect: (selectedMathPlaylist: PlayerPlaylistOption) => void,
  players: {
    team1: PlayerPlaylistOptions,
    team2: PlayerPlaylistOptions,
  },
  profile: MatchInfo,
  selectedMathPlaylist?: PlaylistOption,
}

export const PlayersPlaylists = ({
  onSelect,
  players,
  profile,
  selectedMathPlaylist,
}: Props) => {
  const { sportType } = usePageParams()
  const [selectedTeam, setSelectedTeam] = useState(Teams.TEAM1)

  if (!profile) return null

  return (
    <Wrapper>
      <Tabs>
        <Tab
          active={selectedTeam === Teams.TEAM1}
          onClick={() => setSelectedTeam(Teams.TEAM1)}
        >
          <Name nameObj={profile.team1} prefix='abbrev_' />
        </Tab>
        <Tab
          active={selectedTeam === Teams.TEAM2}
          onClick={() => setSelectedTeam(Teams.TEAM2)}
        >
          <Name nameObj={profile.team2} prefix='abbrev_' />
        </Tab>
      </Tabs>
      <List>
        {
          map(players[selectedTeam], (player) => (
            <PlayersItem key={player.id}>
              <PlayButton
                active={isEqual(player, selectedMathPlaylist)}
                duration={player.dur}
                onClick={() => onSelect(player)}
                leftContent={(
                  <PlayerAvatar
                    id={player.id}
                    profileType={ProfileTypes.PLAYERS}
                    sportType={sportType}
                  />
                )}
              >
                <PlayerNum>{player.num}</PlayerNum>
                <Name nameObj={player} />
              </PlayButton>
            </PlayersItem>
          ))
        }
      </List>
    </Wrapper>
  )
}
