// @flow
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';

type Props = {
  +className?: string;
  +name: string;
  +src: string;
}

const ProfilePictureWrapper = styled.figure`
  display: flex;
  justify-content: center;
  background-color: ${({ backgroundcolor }) => backgroundcolor};
  position: relative;
  align-items: center;
  height: 100%;
  width: 100%;
  border-radius: 50%;
`;

const ProfileImage = styled.img`
  border-radius: 50%;
  min-width: 100%;
  height: 100%;
`;

const Empty = styled.span`
  display: none;
`;

/**
 * Take a name, split it by whitespace, return the first letter of first background
 * Last elements. Upcaseboth!
 */
const initials = (name: string) => {
  const nameSplit = name && name.split(' ');
  if (Array.isArray(nameSplit) && nameSplit.length > 1 && nameSplit[0] !== '') {
    return nameSplit[0][0] + nameSplit[nameSplit.length - 1][0];
  }
  if (name) {
    return name.substr(0, 1);
  }
  return '';
};

const hexBackground = (name: string) => {
  const colors = [
    '#5AB6A3',
    '#A2D7AF',
    '#806056',
    '#3962B3',
  ];
  const i = initials(name);
  if (i !== '') {
    const index = Math.abs(Math.floor(Math.sin(i.charCodeAt(0)) * 2) - 1);
    const color = colors[index];
    if (color) {
      return color;
    }
  }
  return '#5AB6A3';
};

/**
 * A profile picture
 */
const ProfilePicture = ({ className, src, name }: Props) => {
  const [imageError, setImageError] = useState(false);
  const userInitialCanvas = React.createRef();

  useEffect(() => {
    const canvas = userInitialCanvas.current;
    if (!canvas) {
      return;
    }

    const context = canvas.getContext('2d');
    const xSize = 256;
    const ySize = 256;
    if (typeof window !== 'undefined' && window.devicePixelRatio) {
      canvas.width = xSize * window.devicePixelRatio;
      canvas.height = ySize * window.devicePixelRatio;
      context.scale(window.devicePixelRatio, window.devicePixelRatio);
    }

    context.fillStyle = hexBackground(name);
    context.fillRect(0, 0, xSize, ySize);
    context.font = `${xSize / 3}px Arial`;
    context.textAlign = 'center';
    context.fillStyle = '#FFF';
    context.fillText(initials(name), xSize / 2, ySize / 1.6);
  }, [name, userInitialCanvas]);

  return (
    <ProfilePictureWrapper className={className}>
      { typeof src === 'string' && src !== ''
        ? (
          <ProfileImage
            onError={(event) => {
              event.target.setAttribute('style', 'display:none;');
              setImageError(true);
            }}
            alt={name}
            src={src}
          />
        )
        : <Empty />
      }
      {(typeof src !== 'string' || src === '' || imageError) && (
        <canvas
          ref={userInitialCanvas}
          style={{
            // Styled component doesn't work here, it gets in the way of the canvas
            // so we provide required style inline instead
            display: 'flex',
            overflow: 'hidden',
            width: '100%',
            height: '100%',
            borderRadius: '50%',
          }}
        />
      )}
    </ProfilePictureWrapper>
  );
};

ProfilePicture.defaultProps = {
  className: '',
};

export default ProfilePicture;
