import { useState } from 'react'

import map from 'lodash/map'
import sortBy from 'lodash/sortBy'

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

import { isMobileDevice } from 'config/userAgent'

import { Radio as RadioBase } from 'features/Common'
import { Label } from 'features/Common/Radio/styled'
import { RadioSvg } from 'features/Common/Radio/Icon'
import { useCardsStore } from 'features/CardsStore'

const List = styled.ul`
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  :not(:empty) {
    margin-bottom: 10px;
  }
`

const Item = styled.li`
  width: 50%;
  height: 50px;
  display: flex;
  align-items: center;
  ${isMobileDevice
    ? css`
      width: 100%;
      height: 21px;
      /* margin-bottom: 14px; */
    `
    : ''}
`

const Radio = styled(RadioBase)`
  ${Label} {
    font-weight: normal;
    font-size: 14px;
    line-height: 21px;
    ${isMobileDevice
    ? css`
      font-size: 12px;
      line-height: 100%;
    `
    : ''}
  }

  ${RadioSvg} {
    margin-right: 12px;
    ${isMobileDevice
    ? css`
      /* margin-right: 18px; */
      width: 16px;
      height: 16px;
    `
    : ''}
  }
`

export const CardsList = () => {
  const {
    cards,
    defaultCard,
    onSetDefaultCard,
  } = useCardsStore()

  const [activeCard, setActiveCard] = useState(defaultCard?.id)

  return (
    <List>
      {
        map(sortBy(cards, ['last4']), (card) => (
          <Item key={card.id}>
            <Radio
              label={`${card.brand} •••• ${card.last4}`}
              checked={card.id === activeCard}
              onChange={() => {
                setActiveCard(card.id)
                onSetDefaultCard(card.id)
              }}
            />
          </Item>
        ))
      }
    </List>
  )
}
