import type { CSSProperties } from 'react'
import type { ListChildComponentProps } from 'react-window'
import styled from 'styled-components/macro'

import floor from 'lodash/floor'

import type { Tournament, Tournaments } from 'requests'

import { isMobileDevice } from 'config/userAgent'

import { TournamentInfo } from '../TournamentInfo'
import { Checkbox } from '../../styled'

const Item = styled.li`
  width: 48.5%;
  padding: 6.5px 0;
`

const getTwoColumnListStyles = (index: number) => {
  const isEven = index % 2 === 0
  const rowIndex = floor(index / 2)
  const style: CSSProperties = {
    position: 'absolute',
    top: 48 * rowIndex,
  }
  if (isEven) {
    style.left = 0
  } else {
    style.right = 0
  }
  return style
}

export type ItemData = {
  isTournamentSelected: (tournament: Tournament) => boolean,
  onTournamentSelect: (tournament: Tournament) => void,
  tournaments: Tournaments,
}

export const TournamentListItem = ({
  data,
  index,
  style,
}: ListChildComponentProps<ItemData>) => {
  const {
    isTournamentSelected,
    onTournamentSelect,
    tournaments,
  } = data
  const tournament = tournaments[index]
  if (!tournament) return null

  return (
    <Item style={isMobileDevice ? style : getTwoColumnListStyles(index)}>
      <Checkbox
        checked={isTournamentSelected(tournament)}
        label={<TournamentInfo tournament={tournament} />}
        onChange={() => onTournamentSelect(tournament)}
      />
    </Item>
  )
}
