import type { FC } from 'react';
import React from 'react';
import cx from 'classnames';
import { Image } from '../image';

const BG_COLORS: string[] = [
    'midnight-5',
    'blue',
    'teal',
    'purple',
    'pink',
    'orange',
    'cyan',
    'sky-blue',
];

const CLASSNAME = 'UserThumb';

const getBackgroundColorClass = (initials: string) => {
    const asciiSum = initials.charCodeAt(0);
    const backgroundIndex = asciiSum % BG_COLORS.length;
    const backgroundColor = BG_COLORS[backgroundIndex];
    if (backgroundColor) return `bg-${backgroundColor}`;
    return undefined;
};

const upperFirst = (value: string) => value[0]?.toUpperCase() ?? '';

const getThumbTitle = (name: string) => {
    const [first, ...rest] = name.split(' ');
    const last = rest[rest.length - 1];

    if (first && last) return `${upperFirst(first)}${upperFirst(last)}`;
    return upperFirst(first);
};

const InitialsPlaceholder: FC<{ initials: string }> = ({ initials }) => (
    <div className={`${CLASSNAME}-placeholder`}>
        <div className={`${CLASSNAME}-title`}>{initials}</div>
    </div>
);

export interface UserThumbProps {
    /** User image url */
    image?: string;
    /** Full user name that will get shorten to initials */
    name?: string;
}

/**
 * UserThumb is our container for user's profile picture. It provides various sizes and contains a placeholder visual using a plain colour and user's initials.
 *
 * @type atom
 * @status live
 * @tags visuals
 */
export const UserThumb: FC<UserThumbProps> = ({ image, name }) => {
    const initials = getThumbTitle(name ?? '');
    const BG_CLASS = getBackgroundColorClass(initials);

    const InitPlaceholder = <InitialsPlaceholder initials={initials} />;

    return (
        <div className={cx(CLASSNAME, BG_CLASS)}>
            {!image ? (
                InitPlaceholder
            ) : (
                <Image
                    alt={initials}
                    className={`${CLASSNAME}-image`}
                    src={image}
                    placeholder={InitPlaceholder}
                />
            )}
        </div>
    );
};
