import React, {Component} from 'react'
import {MdKeyboardArrowDown} from 'react-icons/lib/md'
import Spinner from 'react-spinjs'
import styled from 'styled-components'
import Hover from 'components/utils/hover'
import auto_bind from 'common/auto_bind'
import {color, link, disabled_link, circle} from 'common/styles'

export default class SecondaryActions extends Component {
  constructor(props) {
    super(props)
    auto_bind(this)
  }

  render_action({onClick, label, badge, loading, disabled}, id) {
    return (
      <Action onClick={!loading && !disabled && onClick} key={id} disabled={disabled}>
        {label}
        {badge ? (
          <Badge>
            {badge}
          </Badge>
        ) : null}
        {loading ? (
          <Loading>
            <Spinner config={{length: 4, width: 2, radius: 5}} />
          </Loading>
        ) : null}
      </Action>
    )
  }

  render() {
    let {children: actions, active} = this.props
    return (
      <Hover>
        {(hover) => (
          <Container>
            <Label active={active}>
              Action <MdKeyboardArrowDown />
            </Label>
            {hover ? (
              <Actions>
                {actions.map(this.render_action)}
              </Actions>
            ) : null}
          </Container>
        )}
      </Hover>
    )
  }
}

const Container = styled.div`
  padding: 6px;
  z-index: auto;
  position: relative;
`

const Label = styled.div`
  font-size: 16px;
  color: color(black, light);
  text-transform: uppercase;
  ${({active}) => active ? `color: ${color('action')};` : ''}
  white-space: nowrap;
`

const Actions = styled.div`
  position: absolute;
  right: 0;
  top: 100%;
  width: 300px;
  z-index: 1;
  background-color: white;
  box-shadow: 0 1px 2px 1px ${color('black', 'bright')};
  padding: 5px 0;
`

const Action = styled.div`
  padding: 8px 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  ${({onClick, disabled}) => disabled ? `
    opacity: 0.54;
    ${disabled_link}
  ` : (onClick ? `
    ${link}
    &:hover {
      opacity: 1;
      background-color: ${color('black', 'pale')};
    }
  ` : '')}
`

const Loading = styled.div`
  width: 20px;
  height: 20px;
  position: relative;
`

const Badge = styled.div`
  ${circle(20)}
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  background-color: ${color('action')};
`
