import React from 'react';
import { Icon } from 'lego-on-react';
import block from 'bem-cn';
import BetaIcon from 'components/Icon/Beta';
import ServiceStatus from 'components2/ServiceStatus';
import ServiceToggle from 'components2/ServiceToggle';
import getService from 'lib2/getService';
import { ServiceStore } from 'lib2/stores';
import { i18n } from 'i18n2';

import './index.css';

const b = block('service-header');

export default class ServiceHeader extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {};
    }

    componentDidMount() {
        this._update();
        this._storeListener = ServiceStore.onChange(() => this._update());
    }

    componentWillUnmount() {
        this._storeListener.remove();
    }

    componentDidUpdate(prevProps) {
        if (this.props.serviceSlug !== prevProps.serviceSlug) {
            this._update();
        }
    }

    _update() {
        let { enabled, ready } = getService(this.props.serviceSlug);

        this.setState({
            enabled,
            ready,
        });
    }

    render() {
        let { serviceSlug, actions, badge, cls } = this.props;
        let { enabled, ready } = this.state;

        let service = getService(serviceSlug);

        return (
            <div className={b.mix(cls)}>
                <div className={b('top')}>
                    <Icon
                        cls={b('icon')}
                        url={service.icon}
                    />
                    <div className={b('title-container')}>
                        <div className={b('title')}>
                            <span className={b('name')}>
                                {service.name}
                            </span>
                            {service.beta && <Icon cls={b('beta-icon')}><BetaIcon /></Icon>}
                            {badge}
                        </div>
                        <div className={b('status')}>
                            <ServiceStatus serviceSlug={serviceSlug} />
                        </div>
                    </div>
                    <div className={b('actions')}>
                        {enabled && ready && actions}
                        <ServiceToggle serviceSlug={serviceSlug} />
                    </div>
                </div>
                <div
                    className={b('description')}
                    dangerouslySetInnerHTML={{
                        __html: i18n(`service_page.${serviceSlug}.description`),
                    }}
                />
            </div>
        );
    }
}
