import React from 'react';
import block from 'bem-cn';
import TrialStatus from 'const2/TrialStatus';
import getService from 'lib2/getService';
import isPartnerOrganization from 'lib2/isPartnerOrganization';
import getPath from 'lib2/getPath';
import { ServiceStore, PricingStore } from 'lib2/stores';
import { i18n, formatDate, formatCurrency } from 'i18n2';
import Badge from './Badge';

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

const EXPIRING_TRIAL_WARNING_DAYS = 14;

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

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

        this.state = {};

        this._update = this._update.bind(this);
    }

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

        this.setState({
            enabled,
            ready,
            trial,
            pricing: PricingStore.get(['services', serviceSlug]),
            currency: PricingStore.get('currency'),
        });
    }

    componentDidMount() {
        this._update();

        this._storeListeners = [
            ServiceStore.onChange(this._update),
            PricingStore.onChange(this._update),
        ];
    }

    componentWillUnmount() {
        this._storeListeners.forEach(listener => listener.remove());
    }

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

    render() {
        const { serviceSlug, cls, size } = this.props;
        const { enabled, ready, trial = {}, pricing = {}, currency } = this.state;

        const {
            canShowTrialStatus,
            canShowReadOnly,
            canShowPricing,
        } = this.props;

        if (canShowTrialStatus && trial.status === TrialStatus.IN_PROGRESS && trial.expiration_date) {
            let color;

            if (trial.days_till_expiration < EXPIRING_TRIAL_WARNING_DAYS) {
                color = 'red';
            } else {
                color = enabled && ready ? 'green' : 'gray';
            }

            return (
                <Badge
                    cls={b({ type: 'trial' }).mix(cls)}
                    htmlTip={getText(serviceSlug, 'status.free_until_tip')}
                    color={color}
                    size={size}
                >
                    {getText(serviceSlug, 'status.free_until', {
                        date: formatDate(trial.expiration_date, 'short'),
                    })}
                </Badge>
            );
        }

        // нет подписок - режим "только чтение"
        if (canShowReadOnly && enabled && ready && pricing.users_count === 0) {
            return (
                <Badge
                    cls={b({ type: 'readonly' }).mix(cls)}
                    htmlTip={getText(serviceSlug, 'status.ro_tip', {
                        settings_url: getPath('services', serviceSlug),
                    })}
                    color="red"
                    size={size}
                >
                    {getText(serviceSlug, 'status.ro')}
                </Badge>
            );
        }

        if (canShowPricing && !isPartnerOrganization() && enabled && ready && pricing.users_count > 0) {
            let price = formatCurrency(pricing.total, currency);

            if (typeof pricing.total_with_discount === 'number') {
                price = formatCurrency(pricing.total_with_discount, currency);
            }

            return (
                <Badge
                    cls={b({ type: 'price' }).mix(cls)}
                    htmlTip={getText(serviceSlug, 'status.per_month_tip')}
                    color="blue"
                    size={size}
                >
                    <span
                        dangerouslySetInnerHTML={{
                            __html: getText(serviceSlug, 'status.per_month', { price }),
                        }}
                    />
                </Badge>
            );
        }

        return null;
    }
}
