import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import Image from '../image/Image';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/Avatar.scss';

const n = createNamespace('Avatar');

const getNameInitials = fullName => fullName && fullName.match(/\b(\w)/g)?.map(letter => letter.toUpperCase()).join('');

const Avatar = ({
    name,
    className,
    picture,
    size,
    borderRadius,
    ...otherProps
}) => {
    // show picture or initials when picture is missing
    let content = null;
    if (picture) {
        content = <Image src={picture} alt={name} {...n('image').props} />;
    } else {
        content = <span {...n('initial').withTestId().props} aria-hidden="true">{getNameInitials(name)}</span>;
    }

    const cssVariables = {
        size: size && `${size}px`,
        'border-radius': borderRadius && `${borderRadius}px`
    };
    const wrapperModifier = picture ? 'with-picture' : 'with-initials';
    const specificProps = n('wrapper', wrapperModifier).withClass(className).withVariables(cssVariables).withTestId().props;

    return (
        <div {...otherProps} {...specificProps}>{content}</div>
    );
};

Avatar.propTypes = {
    className: PropTypes.string,
    name: PropTypes.string,
    picture: PropTypes.string,
    size: PropTypes.number,
    borderRadius: PropTypes.number
};

Avatar.defaultProps = {
    className: '',
    name: '',
    picture: null,
    size: null,
    borderRadius: null
};

export default Avatar;
