import React from 'react';
import { Spin } from 'lego-on-react';
import { block } from 'bem-cn';
import PricingDetails from 'components2/PricingDetails';
import DiscountedPrice from 'components2/DiscountedPrice';
import toDataObject from 'lib2/toDataObject';
import { PricingStore } from 'lib2/stores';
import isPartnerOrganization from 'lib2/isPartnerOrganization';
import directory from 'api2/directory';
import { i18n, pluralize, formatNumber } from 'i18n2';

const b = block('calculated-service-pricing');

const BlankState = {
    per_user: undefined,
    per_user_with_discount: undefined,
    total: undefined,
    total_with_discount: undefined,
    user_count: undefined,
    promocode: undefined,
};

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

        this.state = {
            busy: true,
        };
    }

    componentDidMount() {
        this._update();
    }

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

    _update() {
        let {
            serviceSlug,
            existingSubscribers = [],
            selectedSubscribers = new Map(),
        } = this.props;

        this.setState({
            busy: true,
        });

        directory.send('POST', `/v11/subscription/services/${serviceSlug}/licenses/calculate-price/`, {
            body: JSON.stringify([
                ...selectedSubscribers.values(),
                ...existingSubscribers,
            ].map(toDataObject)),
        })
            .then(({ ok, body }) => {
                this.setState(ok ? body : BlankState);
            })
            .finally(() => {
                this.setState({
                    busy: false,
                });
            });
    }

    render() {
        let { serviceSlug } = this.props;
        let { state } = this;

        let currency = PricingStore.get('currency');
        let shouldRenderPrices = !isPartnerOrganization();

        return (
            <PricingDetails
                cls={b()}
                busy={state.busy}
            >
                {shouldRenderPrices &&
                <PricingDetails.Slot
                    description={i18n('service_page.default.plan.total_per_month')}
                    tip={typeof state.total === 'number' &&
                        i18n(`service_page.${serviceSlug}.status.per_month_tip`)}
                >
                    <DiscountedPrice
                        currency={currency}
                        price={state.total}
                        priceWithDiscount={state.total_with_discount}
                    />
                </PricingDetails.Slot>}
                {typeof state.user_count === 'number' &&
                <PricingDetails.Slot
                    description={pluralize(
                        state.user_count,
                        i18n('common.users'),
                        '${objects}'
                    )}
                    tip={i18n('service_page.default.calculated_count_tip')}
                >
                    {formatNumber(state.user_count)}
                </PricingDetails.Slot>}
                <Spin
                    progress={state.busy}
                    size="m"
                    position="center"
                />
            </PricingDetails>
        );
    }
}
