import { useMemo } from 'react'

import styled, { css } from 'styled-components/macro'

import filter from 'lodash/filter'
import isEmpty from 'lodash/isEmpty'
import map from 'lodash/map'

import { isMobileDevice } from 'config/userAgent'

import type { MatchPlaylistOptions, PlaylistOption } from 'features/MatchPage/types'
import { FULL_GAME_KEY } from 'features/MatchPage/helpers/buildPlaylists'
import { isEqual } from 'features/MatchSidePlaylists/helpers'
import { T9n } from 'features/T9n'

import { PlayButton } from '../PlayButton'

type Props = {
  live?: boolean,
  onSelect?: (selectedMathPlaylist: PlaylistOption) => void,
  playlists: MatchPlaylistOptions,
  selectedMathPlaylist?: PlaylistOption,
}

const List = styled.ul``

const Item = styled.li`
  margin-bottom: 12px;
  width: 100%;
  height: 36px;
  ${isMobileDevice
    ? css`
      height: 32px;
      margin-bottom: 9px;
    `
    : ''};
`

export const MatchPlaylists = ({
  live,
  onSelect,
  playlists,
  selectedMathPlaylist,
}: Props) => {
  const filteredPlayListByDuration = useMemo(() => (
    filter(playlists, (playlist) => (
      live
        ? Boolean(playlist.duration) || (playlist.id === 'full_game')
        : Boolean(playlist.duration)
    ))
  ), [playlists, live])

  return (
    <List>
      {
        map(filteredPlayListByDuration, (playlist) => (
          <Item key={playlist.id}>
            <PlayButton
              duration={playlist.duration}
              active={isEqual(playlist, selectedMathPlaylist)}
              live={live}
              disabled={playlist.id !== FULL_GAME_KEY && isEmpty(playlist.episodes)}
              onClick={() => onSelect?.(playlist)}
            >
              <T9n t={playlist.lexic} />
            </PlayButton>
          </Item>
        ))
      }
    </List>
  )
}
