import React from 'react';
import buildString from '@connect/string-placeholders';
import block from 'bem-cn';
import PricingDetails from 'components2/PricingDetails';
import DiscountedPrice from 'components2/DiscountedPrice';
import TrialStatus from 'const2/TrialStatus';
import { PricingStore, ServiceStore } from 'lib2/stores';
import getService from 'lib2/getService';
import directory from 'api2/directory';
import { i18n, pluralize, formatDate, formatNumber } from 'i18n2';

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

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

        this.state = {
            busy: true,
        };

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

    componentDidMount() {
        this._update();

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

        if (!PricingStore.get(['services', this.props.serviceSlug])) {
            directory
                .send('GET', '/v11/subscription/pricing/')
                .then(({ body }) => {
                    PricingStore.mergeState(body);
                })
                .finally(() => {
                    if (!this._unmounted) {
                        this.setState({ busy: false });
                    }
                });
        } else if (!this._unmounted) {
            this.setState({ busy: false });
        }
    }

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

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

    _update() {
        let { serviceSlug } = this.props;

        this.setState({
            hashKey: JSON.stringify([
                getService(serviceSlug),
                PricingStore.get(['services', serviceSlug]),
            ]),
        });
    }

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

        if (trial.status === TrialStatus.IN_PROGRESS) {
            return (
                <PricingDetails.Slot
                    description={(
                        trial.expiration_date ?
                            i18n('service_page.default.plan.trial_until_date', {
                                date: formatDate(trial.expiration_date, 'short'),
                            }) :
                            ''
                    )}
                >
                    {i18n('service_page.default.plan.trial_in_progress')}
                </PricingDetails.Slot>
            );
        }

        if (!enabled || !ready) {
            let freeSubscriptions = options && options.free_subscriptions;

            if (typeof freeSubscriptions !== 'number') {
                return null;
            }

            return (
                <PricingDetails.Slot
                    description={buildString(
                        pluralize(
                            freeSubscriptions,
                            i18n('service_page.default.plan.up_to_n_licenses'),
                            '${objects}'
                        ),
                        { n: freeSubscriptions }
                    )}
                >
                    {i18n('service_page.default.plan.free')}
                </PricingDetails.Slot>
            );
        }

        let pricing = PricingStore.get(['services', serviceSlug]) || {};
        let currency = PricingStore.get('currency');

        let { busy, hashKey } = this.state;

        return (
            <PricingDetails
                title={i18n('service_page.default.plan.title')}
                cls={b()}
                busy={busy}
                progress={busy}
                key={hashKey}
            >
                <PricingDetails.Slot
                    description={i18n('service_page.default.plan.total_per_month')}
                    tip={typeof pricing.total === 'number' &&
                        i18n(`service_page.${serviceSlug}.status.per_month_tip`)}
                >
                    <DiscountedPrice
                        currency={currency}
                        price={pricing.total}
                        priceWithDiscount={pricing.total_with_discount}
                    />
                </PricingDetails.Slot>
                {typeof pricing.users_count === 'number' &&
                <PricingDetails.Slot
                    description={pluralize(
                        pricing.users_count,
                        i18n('common.users'),
                        '${objects}'
                    )}
                >
                    {formatNumber(pricing.users_count)}
                </PricingDetails.Slot>}
            </PricingDetails>
        );
    }
}
