import React from 'react';
import block from 'bem-cn';
import { Link, Icon } from 'lego-on-react';
import ConnectIcon from 'components/Icon/Connect';
import { i18n, formatCurrency, pluralize } from 'i18n2';
import { ServiceStore, PricingStore, BalanceStore } from 'lib2/stores';
import getService from 'lib2/getService';
import BilledServices from 'const2/BilledServices';
import TrialStatus from 'const2/TrialStatus';

import './index.css';

const b = block('paid-services');

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

        this.state = {};

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

    componentDidMount() {
        this._onStoreChange();
        this._storeListeners = [
            PricingStore.onChange(this._onStoreChange),
            ServiceStore.onChange(this._onStoreChange),
            BalanceStore.onChange(this._onStoreChange),
        ];
    }

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

    _onStoreChange() {
        this.setState({
            hashKey: JSON.stringify([
                ServiceStore.get('map'),
                PricingStore.get('services'),
                BalanceStore.get('subscription_plan'),
            ]),
        });
    }

    render() {
        const { hashKey } = this.state;
        const plan = BalanceStore.get('subscription_plan');

        let services = BilledServices
            .map(serviceSlug => getService(serviceSlug))
            .filter(({ slug, available, enabled, ready, trial = {} }) => {
                const pricing = PricingStore.get(['services', slug]) || {};

                return available && enabled && ready &&
                    (!trial || trial.status !== TrialStatus.IN_PROGRESS) && pricing.total !== undefined;
            });

        return (
            <div
                className={b({}).mix(this.props.cls)}
                key={hashKey}
            >
                {!services.length && (
                    <React.Fragment>
                        <h3 className={b('placeholder-title')}>
                            {i18n('balance.services.placeholder.title')}
                        </h3>
                        <span
                            dangerouslySetInnerHTML={{
                                __html: i18n('balance.services.placeholder.description', {
                                    services_url: '/portal/home',
                                }),
                            }}
                        />
                    </React.Fragment>
                )}
                {services.map(({ slug, url, name, icon, settings_url: settingsUrl }) => (
                    <PaidService
                        key={slug}
                        serviceSlug={slug}
                        url={url}
                        name={name}
                        settingsUrl={settingsUrl}
                        icon={icon}
                    />
                ))}
                {plan === 'paid' && (
                    <PaidService
                        key="connect"
                        serviceSlug="connect"
                        url="/portal/home"
                        name={i18n('balance.services.name.connect')}
                    />
                )}
            </div>
        );
    }
}

const PaidService = ({ serviceSlug, url, name, icon, settingsUrl }) => {
    const pricing = PricingStore.get(['services', serviceSlug]) || {};
    const currency = PricingStore.get('currency');

    const price = formatCurrency(
        typeof pricing.total_with_discount === 'number' ?
            pricing.total_with_discount :
            pricing.total,
        currency
    );

    return (
        <div className={b('item')} key={serviceSlug}>
            {icon ? (
                <Icon
                    cls={b('icon')}
                    url={icon}
                />
            ) : (
                <Icon cls={b('icon')}>
                    <ConnectIcon />
                </Icon>
            )}
            <div className={b('details')}>
                <div className={b('title')}>
                    <Link
                        url={url}
                        theme="black"
                    >
                        {name}
                    </Link>
                </div>
                <div className={b('pricing')}>
                    <div
                        className={b('price')}
                        dangerouslySetInnerHTML={{
                            __html: i18n('balance.services.monthly_price.total', { price }),
                        }}
                    />
                    {typeof pricing.users_count === 'number' && settingsUrl && (
                        <div className={b('note')}>
                            <Link
                                url={settingsUrl}
                                theme="black"
                            >
                                <span
                                    dangerouslySetInnerHTML={{
                                        __html: i18n('balance.services.current_subscriptions', {
                                            n_subscriptions: pluralize(pricing.users_count,
                                                serviceSlug === 'connect' ?
                                                    i18n('balance.services.persons') :
                                                    i18n('balance.services.subscriptions')
                                            ),
                                        }),
                                    }}
                                />
                            </Link>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
