import React from 'react';

import {FormattedMessage, useIntl} from 'react-intl';

import {useSelector} from 'react-redux';
import {getUser} from 'mattermost-redux/selectors/entities/users';
import {GlobalState} from 'mattermost-redux/types/store';
import {UserProfile} from 'mattermost-redux/types/users';

import {Ownership} from '../../types/badges';

import './user_row.scss';

type Props = {
    ownership: Ownership;
    onClick: (user: string) => void;
}

const UserBadgeRow: React.FC<Props> = ({ownership, onClick}: Props) => {
    const intl = useIntl();
    const user = useSelector<GlobalState, UserProfile>((state) => getUser(state, ownership.user));
    const grantedBy = useSelector<GlobalState, UserProfile>((state) => getUser(state, ownership.granted_by));

    if (!user) {
        return null;
    }

    let grantedByName = intl.formatMessage({id: 'badges.unknown', defaultMessage: 'неизвестно'});
    if (grantedBy) {
        grantedByName = '@' + grantedBy.username;
    }

    const time = new Date(ownership.time);
    return (
        <div
            className='UserRow'
            onClick={() => onClick(ownership.user)}
        >
            <div className='badge-user-username'>
                <a>{`@${user.username}`}</a>
            </div>
            <div className='badge-user-meta'>
                <FormattedMessage
                    id='badges.label.granted_by'
                    defaultMessage='Выдал: {username}'
                    values={{username: grantedByName}}
                />
                {' · '}
                <FormattedMessage
                    id='badges.label.granted_at'
                    defaultMessage='Выдан: {date}'
                    values={{date: intl.formatDate(time, {day: '2-digit', month: '2-digit', year: 'numeric'})}}
                />
            </div>
        </div>
    );
};

export default UserBadgeRow;
