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

import { block } from 'bem-cn';

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

import { i18n, formatCurrency, formatDate, pluralize } from 'lib/i18n';
import template from 'lib/template';

import Tip from 'ui/Tip/index';
import Icon from 'ui/Icon/index';

import './index.css';

const bServicePlan = block('service-plan');

const FREE_LICENSES_COUNT = 5;

const ServicePlan = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

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

        const pricing = SubscriptionStore.getPricing(serviceSlug);
        const currency = _.get(pricing, 'currency', 'RUB');
        const serviceData = AuthStore.getService(serviceSlug) || {};

        return {
            isEnabled: AuthStore.isServiceEnabled(serviceSlug),
            usersCount: SubscriptionStore.getCurrentUserCount(serviceSlug),
            trialStatus: AuthStore.getServiceTrialStatus(serviceSlug),
            pricePerUser: this._formatPrice(pricing.per_user, currency),
            pricePerUserWithDiscount: this._formatPrice(pricing.per_user_with_discount, currency),
            totalPrice: this._formatPrice(pricing.total, currency),
            totalPriceWithDiscount: this._formatPrice(pricing.total_with_discount, currency),
            trialExpirationDate: _.get(serviceData.trial, 'expiration_date'),
            promoCode: SubscriptionStore.getAvailablePromoCodes()[0],
        };
    },

    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);
    },

    _formatPrice(price, currency) {
        return typeof price === 'number' && formatCurrency(price, currency);
    },

    _getPriceDescription() {
        const { isEnabled, trialStatus, trialExpirationDate } = this.state;
        const isTrial = trialStatus === TRIAL_STATUS.IN_PROGRESS;

        if (!isTrial) {
            // Если бесплатно, то пишем для скольких лицензий
            if (!isEnabled) {
                return template.build(
                    pluralize(FREE_LICENSES_COUNT, this._getText('plan.up_to_n_licenses'), '${objects}'), {
                        n: FREE_LICENSES_COUNT,
                    }
                );
            }

            return this._getText('plan.per_one_user_per_month');
        }

        const untilText = this._getText('plan.trial_until_date', {
            date: formatDate(trialExpirationDate, 'day-and-month'),
        });

        return <span dangerouslySetInnerHTML={{ __html: untilText }} />;
    },

    _renderPriceTooltip() {
        const { promoCode, pricePerUserWithDiscount, trialStatus } = this.state;

        if (!promoCode || !pricePerUserWithDiscount || trialStatus === TRIAL_STATUS.IN_PROGRESS) {
            return null;
        }

        return (
            <div className={bServicePlan('cost-info')}>
                <Icon type="question" />
                <Tip theme="light">
                    <div className={bServicePlan('promocode-tooltip')}>
                        <div className={bServicePlan('promocode-description')}>
                            {promoCode.id}
                            <br />
                            {promoCode.description}
                        </div>
                    </div>
                </Tip>
            </div>
        );
    },

    _renderTotalPriceTooltip() {
        return (
            <div className={bServicePlan('cost-info')}>
                <Icon type="question" />
                <Tip theme="light">
                    <div className={bServicePlan('total-price-tooltip')}>
                        <div className={bServicePlan('total-price-description')}>
                            {this._getText('status.per_month_tip')}
                        </div>
                    </div>
                </Tip>
            </div>
        );
    },

    _getPrice() {
        const { isEnabled, trialStatus, pricePerUser, pricePerUserWithDiscount } = this.state;

        if (trialStatus === TRIAL_STATUS.IN_PROGRESS) {
            return this._getText('plan.trial_in_progress');
        }

        if (isEnabled) {
            // Если есть скидка, показываем новую цену и рядом зачёркнутую старую
            return pricePerUserWithDiscount ? pricePerUserWithDiscount + pricePerUser : pricePerUser;
        }

        return this._getText('plan.free');
    },

    _getTotalPrice() {
        const { totalPriceWithDiscount, totalPrice } = this.state;

        return totalPriceWithDiscount ? totalPriceWithDiscount + totalPrice : totalPrice;
    },

    render() {
        const { usersCount, isEnabled, trialStatus } = this.state;
        const isTrial = trialStatus === TRIAL_STATUS.IN_PROGRESS;

        let content = [
            <div className={bServicePlan('item', { role: 'price' })} key="price-item">
                <div className={bServicePlan('text')}>
                    <span
                        className={bServicePlan('cost')}
                        dangerouslySetInnerHTML={{ __html: this._getPrice() || '\u2014' }}
                    />
                    {this._renderPriceTooltip()}
                </div>
                <div className={bServicePlan('description')}>{this._getPriceDescription()}</div>
            </div>,
        ];

        if (typeof usersCount === 'number' && isEnabled && !isTrial) {
            content.push(
                <div className={bServicePlan('item', { role: 'count' })} key="count-item">
                    <div className={bServicePlan('text')}>{usersCount}</div>
                    <div className={bServicePlan('description')}>
                        {pluralize(usersCount, this._getText('plan.count_subscriptions'), '${objects}')}
                    </div>
                </div>
            );
        }

        if (isEnabled && !isTrial) {
            content.push(
                <div
                    className={bServicePlan('item', { role: 'price' })}
                    key="total-price-item"
                >
                    <div className={bServicePlan('text')}>
                        <span
                            className={bServicePlan('cost')}
                            dangerouslySetInnerHTML={{ __html: this._getTotalPrice() || '\u2014' }}
                        />
                        {this._renderTotalPriceTooltip()}
                    </div>
                    <div className={bServicePlan('description')}>
                        {this._getText('plan.total_per_month')}
                    </div>
                </div>
            );
        }

        return (
            <div className={bServicePlan}>
                {content}
            </div>
        );
    },

});

ServicePlan.propTypes = {
    serviceSlug: PropTypes.string.isRequired,
};

export default ServicePlan;
