import type { ForwardedRef } from 'react'
import { forwardRef } from 'react'

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

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'

export const LIST_INDENT = 30

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

const List = styled.ul`
  margin-bottom: ${LIST_INDENT}px;
`

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

  :last-child {
    margin-bottom: 0;
  }
`

export const MatchPlaylists = forwardRef(
  ({
    live,
    onSelect,
    playlists,
    selectedMathPlaylist,
  }: Props,
  ref: ForwardedRef<HTMLUListElement>) => (
    <List ref={ref}>
      {
        map(playlists, (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>
  ),
)
