// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {memo} from 'react';
import {useSelector} from 'react-redux';

import {GlobalState} from 'mattermost-redux/types/store';

import {getEmojiMap} from 'selectors';
import {getEmojiImageUrl} from 'utils/emoji';

interface ComponentProps {
    emojiName: string;
    size?: number;
    emojiStyle?: React.CSSProperties;
}

const FALLBACK_EMOJI = 'question';

const RenderEmoji = ({emojiName, emojiStyle, size = 16}: ComponentProps) => {
    const emojiMap = useSelector((state: GlobalState) => getEmojiMap(state));

    if (!emojiName) {
        return null;
    }

    let emojiFromMap = emojiMap.get(emojiName);
    if (!emojiFromMap) {
        emojiFromMap = emojiMap.get(FALLBACK_EMOJI);
        if (!emojiFromMap) {
            return null;
        }
    }
    const emojiImageUrl = getEmojiImageUrl(emojiFromMap);

    return (
        <span
            className='emoticon'
            data-emoticon={emojiName}
            style={{
                backgroundImage: `url(${emojiImageUrl})`,
                backgroundSize: size,
                height: size,
                width: size,
                maxHeight: size,
                maxWidth: size,
                minHeight: size,
                minWidth: size,
                ...emojiStyle,
            }}
        />
    );
};

export default memo(RenderEmoji);
