import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import iconsMap from 'simple-icons';
import ShareIcon from '@potok/icons/glyph/misc/share';
import Icon from './Icon';

const getBackgroundSize = ({ size }) => {
  let wh;
  const clearNum = unit =>
    parseFloat(size.substring(0, size.length - unit.length));
  if (size.endsWith('rem')) {
    wh = `${clearNum('rem') + 0.5}rem`;
  }
  if (size.endsWith('px')) {
    wh = `${clearNum('px') + 5}px`;
  }
  return `
    width: ${wh};
    height: ${wh};
    flex: 0 0 ${wh};
  `;
};

const InvertedWrapper = styled.span`
  background: ${p => p.background};
  padding: 5px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  ${getBackgroundSize};
`;

const StyledIcon = styled(Icon)`
  flex: ${p => `0 0 ${p.size}`};
`;

const SocialIcon = ({ name, inverted, ...props }) => {
  const iconInfo = iconsMap[name];

  if (!iconInfo) {
    return <ShareIcon size={props.size} />;
  }

  if (inverted) {
    return (
      <InvertedWrapper size={props.size} background={`#${iconInfo.hex}`}>
        <Icon
          secondaryColor={`#FFF`}
          dangerouslySetGlyph={iconInfo.svg}
          {...props}
        />
      </InvertedWrapper>
    );
  }

  return (
    <StyledIcon
      secondaryColor={`#${iconInfo.hex}`}
      dangerouslySetGlyph={iconInfo.svg}
      {...props}
    />
  );
};

SocialIcon.defaultProps = {
  size: '20px',
  inverted: false,
};

SocialIcon.propTypes = {
  /** Social title */
  name: PropTypes.string,
  /** Whether have rounded colored background or not  */
  inverted: PropTypes.bool,
  /** Size of icon. With inverted true - total size is increased by 5px  */
  size: PropTypes.string,
};

export default SocialIcon;
