import React from 'react';

import {FormattedMessage} from 'react-intl';

import {EmojiIndicesByAlias} from 'utils/emoji';

import {BadgeDetails, BadgeID} from '../../types/badges';
import Client from '../../client/api';

import {RHSState} from '../../types/general';
import {IMAGE_TYPE_EMOJI, RHS_STATE_MY, RHS_STATE_OTHER} from '../../constants';
import BadgeImage from '../badge_image/badge_image';

import {markdown} from 'utils/markdown';

import BackButton from '../../components/back_button/back_button';

import RHSScrollbars from './rhs_scrollbars';
import UserRow from './user_row';

import './badge_details.scss';

type Props = {
    badgeID: BadgeID | null;
    currentUserID: string;
    prevView: RHSState;
    actions: {
        setRHSView: (view: RHSState) => void;
        setRHSUser: (user: string | null) => void;
        getCustomEmojiByName: (names: string) => void;
        openEditBadgeModal: (badge: BadgeDetails) => void;
    };
}

type State = {
    loading: boolean;
    badge?: BadgeDetails | null;
}

class BadgeDetailsComponent extends React.PureComponent<Props, State> {
    constructor(props: Props) {
        super(props);

        this.state = {
            loading: true,
        };
    }

    componentDidMount() {
        if (this.props.badgeID === null) {
            return;
        }

        const c = new Client();
        c.getBadgeDetails(this.props.badgeID).then((badge) => {
            this.setState({badge, loading: false});
        });
    }

    componentDidUpdate(prevProps: Props, prevState: State) {
        if (this.state.badge !== prevState.badge && this.state.badge && this.state.badge.image_type === IMAGE_TYPE_EMOJI && !EmojiIndicesByAlias.has(this.state.badge.image)) {
            this.props.actions.getCustomEmojiByName(this.state.badge.image);
        }

        if (this.props.badgeID === prevProps.badgeID) {
            return;
        }

        if (this.props.badgeID === null) {
            return;
        }

        const c = new Client();
        if (!this.state.loading) {
            this.setState({loading: true});
        }

        c.getBadgeDetails(this.props.badgeID).then((badge) => {
            this.setState({badge, loading: false});
        });
    }

    onUserClick = (user: string) => {
        if (user === this.props.currentUserID) {
            this.props.actions.setRHSView(RHS_STATE_MY);
            return;
        }

        this.props.actions.setRHSUser(user);
        this.props.actions.setRHSView(RHS_STATE_OTHER);
    }

    render() {
        const {badge, loading} = this.state;
        if (this.props.badgeID == null) {
            return (<div>
                <FormattedMessage
                    id='badges.badge_not_found'
                    defaultMessage='Достижение не найдено.'
                />
            </div>);
        }

        if (loading) {
            return (<div className='BadgeDetails BadgeDetails--loading'>
                <div className='spinner'/>
            </div>);
        }

        if (!badge) {
            return (<div>
                <FormattedMessage
                    id='badges.badge_not_found'
                    defaultMessage='Достижение не найдено.'
                />
            </div>);
        }

        const content = badge.owners.map((ownership) => {
            return (
                <UserRow
                    key={ownership.time}
                    ownership={ownership}
                    onClick={this.onUserClick}
                />
            );
        });
        return (
            <div className='BadgeDetails'>
                <div className='BadgeDetails__backHeader'>
                    <BackButton
                        targetView={this.props.prevView}
                        onNavigate={this.props.actions.setRHSView}
                    >
                        <FormattedMessage
                            id='badges.rhs.back_to_achievements'
                            defaultMessage='Назад к достижениям'
                        />
                    </BackButton>
                </div>
                <div className='badge-info'>
                    <span className='badge-icon'>
                        <BadgeImage
                            badge={badge}
                            size={48}
                        />
                    </span>
                    <div className='badge-text'>
                        <div className='badge-name'>
                            <span className='badge-label'>
                                <FormattedMessage
                                    id='badges.label.name'
                                    defaultMessage='Название:'
                                />
                            </span>
                            {' '}
                            {badge.name}
                        </div>
                        <div className='badge-description'>
                            <span className='badge-label'>
                                <FormattedMessage
                                    id='badges.label.description'
                                    defaultMessage='Описание:'
                                />
                            </span>
                            {' '}
                            {badge.description ? markdown(badge.description) : '—'}
                        </div>
                        <div className='badge-meta'>
                            <FormattedMessage
                                id='badges.label.type'
                                defaultMessage='Тип: {typeName}'
                                values={{typeName: badge.type_name}}
                            />
                            {' · '}
                            <FormattedMessage
                                id='badges.label.created_by'
                                defaultMessage='Создал: {username}'
                                values={{username: badge.created_by_username}}
                            />
                        </div>
                    </div>
                    {badge.can_edit && (
                        <button
                            className='BadgeDetails__editButton'
                            onClick={() => this.props.actions.openEditBadgeModal(badge)}
                        >
                            <FormattedMessage
                                id='badges.rhs.edit_badge'
                                defaultMessage='Редактировать'
                            />
                        </button>
                    )}
                </div>
                {badge.owners.length > 0 ? (
                    <>
                        <div className='section-title'>
                            <FormattedMessage
                                id='badges.granted_to'
                                defaultMessage='Выдан:'
                            />
                        </div>
                        <RHSScrollbars>{content}</RHSScrollbars>
                    </>
                ) : (
                    <div className='empty-owners'>
                        <FormattedMessage
                            id='badges.not_granted_yet'
                            defaultMessage='Ещё никому не выдан'
                        />
                    </div>
                )}
            </div>
        );
    }
}

export default BadgeDetailsComponent;
