import React from 'react';
import EmojiRegex from 'emoji-regex';
import PropTypes from 'prop-types';
import _ from 'lodash';

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

const Avatar = props => {
  const { children, circular, className, hexColor, size, imgSrc, ...attrs } = props;

  let text;
  if (!imgSrc) text = _.isString(children) ? children.substring(0, 2) : children.props.children;

  const renderChildren = () => {
    if (imgSrc) return <img alt="" className="Avatar-Img" src={imgSrc} />;
    return <span className="Avatar-Text">{text}</span>;
  };

  const isEmoji = () => {
    if (imgSrc) return false;
    return EmojiRegex().test(text);
  };

  const AvatarClasses = [
    'Avatar',
    `Avatar_${size}`,
    className,
    circular && 'Avatar_circular',
    isEmoji() && 'Avatar_emoji',
  ]
    .filter(e => e)
    .join(' ');

  return (
    <div {...attrs} className={AvatarClasses} style={{ background: hexColor }}>
      {renderChildren()}
    </div>
  );
};

Avatar.propTypes = {
  circular: PropTypes.bool,
  className: PropTypes.string,
  hexColor: PropTypes.string,
  imgSrc: PropTypes.string,
  size: PropTypes.oneOf(['sm', 'md', 'lg']),
};

Avatar.defaultProps = {
  hexColor: '#f0f0f0',
  size: 'md',
};

export default Avatar;
