import React from 'react';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components';
import space from 'Components/utils/styles/space';
import useIcon from 'Components/utils/hooks/useIcon';
import iconTypes from 'Components/utils/types/iconTypes';
import {
  secondaryColor,
  grayColor,
  whiteColor,
} from 'Themes/utils/colorPickers';

const buttonSize = ({ size }) => `${2 * size}px`;

const iconPosition = ({ width: size }) => css`
  top: 50%;
  margin-top: -${size / 2}px;
  left: 50%;
  margin-left: -${size / 2}px;
`;

const StyledWrapper = styled.button`
  padding: 0px;
  border: none;
  background: transparent;
  cursor: pointer;
  ${space}

  :focus {
    outline: 0;
  }

  :hover {
    & span {
      &:first-of-type {
        border-color: ${secondaryColor[0.4]};
        background-color: ${secondaryColor[0.2]};
      }

      & svg {
        fill: ${secondaryColor};
      }

      + span {
        color: ${secondaryColor};
      }
    }
  }
`;

const StyledMicroButton = styled.span`
  position: relative;
  display: block;
  border-radius: 50%;
  border-style: solid;
  border-width: thin;
  border-color: ${grayColor};
  background-color: ${whiteColor};
  box-sizing: border-box;
  width: ${buttonSize};
  height: ${buttonSize};
  text-align: center;
  transition: all 0.2s ease-out;
  -webkit-appearance: none;
  -moz-appearance: none;
`;

const StyledLabel = styled.span`
  color: ${grayColor};
  display: block;
  text-align: center;
  margin-top: 6px;
`;

const MicroButton = props => {
  const { icon, size, label } = props;

  const Icon = useIcon(icon, size, iconPosition);

  return (
    <StyledWrapper>
      <StyledMicroButton {...props}>
        <Icon />
      </StyledMicroButton>
      {label && <StyledLabel {...props}>{label}</StyledLabel>}
    </StyledWrapper>
  );
};

MicroButton.propTypes = {
  disabled: PropTypes.bool,
  icon: PropTypes.oneOf(iconTypes).isRequired,
  label: PropTypes.string,
  size: PropTypes.number,
  onClick: PropTypes.func,
};

MicroButton.defaultProps = {
  disabled: false,
  size: 20,
};

MicroButton.displayName = 'MicroButton';

export default MicroButton;
