import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ColorHash from 'color-hash';

import '../base';
import styles from './Avatar.styl';

const colorHash = new ColorHash({ saturation: [0.5, 0.65] });

export default class Avatar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      failedLoading: false
    };
  }

  render() {
    const { name = '', src, isUser, nav, circle, large, small, xsmall, style, editable } = this.props;
    const { failedLoading } = this.state;

    let initials = '';
    const p = name.split(' ');

    p.forEach((str) => {
      const f = str.charAt(0).toUpperCase();
      if (f.match(/^[\wÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]$/)) initials += f;
    });

    initials = initials.length > 3 ? initials.substring(0, 3) : initials;

    let bg = colorHash.hex(name);
    if (isUser || nav) bg = '#003594';

    const classes = classNames({
      [styles.avatar]: true,
      [styles.nav]: nav,
      [styles.editable]: editable,
      [styles.smallFont]: initials.length > 2,
      [styles.circle]: circle,
      [styles.large]: large,
      [styles.small]: small,
      [styles.xsmall]: xsmall
    });

    if (!initials) initials = '...';

    if (src && !failedLoading) {
      return (
        <div className={classes} style={style}>
          <img onError={(e) => this.setState({ failedLoading: true })} src={src} alt={name} />
        </div>
      );
    }

    return <div className={classes} style={{ ...{ backgroundColor: bg }, ...style }}>{initials}</div>;
  }
}

Avatar.propTypes = {
  name: PropTypes.string,
  src: PropTypes.string,
  circle: PropTypes.bool,
  small: PropTypes.bool,
  xsmall: PropTypes.bool,
  editable: PropTypes.bool,
  // eslint-disable-next-line react/forbid-prop-types
  style: PropTypes.object
};

Avatar.defaultProps = {
  name: undefined,
  src: undefined,
  circle: undefined,
  small: undefined,
  xsmall: undefined,
  editable: undefined,
  style: undefined
};
