import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useState, useMemo } from 'react';
import cx from 'classnames';
import theme from './theme.css';
import AvatarOverlay from './AvatarOverlay';
import Box from '../box';
import { Heading4 } from '../typography';
import { colorsWithout } from '../../constants';
var colors = colorsWithout(['neutral']);

var hashCode = function hashCode(hexString) {
  return parseInt(hexString.substr(-5), 16);
};

var AvatarInitials = function AvatarInitials(_ref) {
  var children = _ref.children,
      name = _ref.name,
      editable = _ref.editable,
      id = _ref.id,
      onImageChange = _ref.onImageChange,
      size = _ref.size;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      displayAvatarOverlay = _useState2[0],
      setDisplayAvatarOverlay = _useState2[1];

  var backgroundColor = useMemo(function () {
    if (!id) {
      return 'neutral';
    }

    return colors[Math.abs(hashCode(id)) % colors.length];
  }, [id]);
  var initials = useMemo(function () {
    var splitName = name.split(' ');
    var firstLetter = splitName[0].charAt(0);

    if (splitName.length > 1) {
      var lastLetter = splitName[splitName.length - 1].charAt(0);
      return "".concat(firstLetter).concat(lastLetter);
    }

    return firstLetter;
  }, [name]);

  var handleOnMouseEnter = function handleOnMouseEnter() {
    setDisplayAvatarOverlay(true);
  };

  var handleOnMouseLeave = function handleOnMouseLeave() {
    setDisplayAvatarOverlay(false);
  };

  var shouldShowAvatarOverlay = editable && (size === 'large' || size === 'hero' || size === 'medium' && displayAvatarOverlay);
  return /*#__PURE__*/React.createElement(Box, {
    alignItems: "center",
    backgroundColor: backgroundColor,
    backgroundTint: "normal",
    className: cx(theme['avatar'], theme['avatar-initials']),
    "data-teamleader-ui": "avatar-initials",
    display: "flex",
    justifyContent: "center",
    onMouseEnter: handleOnMouseEnter,
    onMouseLeave: handleOnMouseLeave
  }, /*#__PURE__*/React.createElement(Heading4, {
    className: theme['initials'],
    color: "neutral",
    tint: id ? 'lightest' : 'darkest'
  }, initials), shouldShowAvatarOverlay && /*#__PURE__*/React.createElement(AvatarOverlay, {
    onClick: onImageChange,
    size: size
  }), children && /*#__PURE__*/React.createElement("div", {
    className: theme['children']
  }, children));
};

export default AvatarInitials;