import PropTypes from 'prop-types';
import React from 'react';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';
import SubscriptionStore from 'stores/Subscription';
import AuthStore from 'stores/Auth';
import OrganizationStore from 'stores/Organizations';

import { i18n, formatCurrency } from 'lib/i18n';
import Url from 'lib/Url';

import Badge from './Badge';

const PaymentBadge = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const { serviceSlug } = this.props;

        return {
            isEnabled: AuthStore.isServiceEnabled(serviceSlug),
            pricing: SubscriptionStore.getPricing(serviceSlug),
            usersCount: SubscriptionStore.getCurrentUserCount(serviceSlug),
        };
    },

    componentDidMount() {
        this.subscribe([SubscriptionStore, AuthStore, OrganizationStore]);
    },

    _getText(key, params) {
        const { serviceSlug } = this.props;

        return i18n(`service_page.${serviceSlug}.${key}`, params) ||
            i18n(`service_page.default.${key}`, params);
    },

    render() {
        const { pricing, usersCount, isEnabled } = this.state;
        const { hidePricing, serviceSlug, size, cls } = this.props;
        const price = formatCurrency(pricing.total_with_discount || pricing.total, pricing.currency);
        const isPartnerOrganization = AuthStore.isPartnerOrganization();

        if (!isEnabled) {
            return null;
        }

        let text;
        let tipHtml;
        let color;

        //  Если нет лицензий, то это режим "только чтение"
        if (usersCount === 0 && serviceSlug === 'tracker') {
            text = this._getText('status.ro');
            tipHtml = this._getText('status.ro_tip', {
                settings_url: Url.getServiceSettingsUrl(serviceSlug),
            });
            color = 'red';
        }

        // Не показываем бейдж с ценой, если это партнерская организация
        if (usersCount > 0 && !hidePricing && !isPartnerOrganization) {
            text = (
                <span
                    dangerouslySetInnerHTML={{
                        __html: this._getText('status.per_month', { price }),
                    }}
                />
            );

            tipHtml = this._getText('status.per_month_tip');
            color = 'blue';
        }

        const tipText = tipHtml && <span dangerouslySetInnerHTML={{ __html: tipHtml }} />;

        return <Badge cls={cls} color={color} tipText={tipText} text={text} size={size} />;
    },

});

PaymentBadge.propTypes = {
    serviceSlug: PropTypes.string.isRequired,
    hidePricing: PropTypes.bool,
};

export default PaymentBadge;
