import React from 'react';
import { Redirect } from 'react-router-dom';
import { block } from 'bem-cn';
import { i18n } from 'i18n2';

import { RouteTiming } from 'lib2/rum';
import { BalanceStore, PricingStore } from 'lib2/stores';
import getHelpUrl from 'lib2/getHelpUrl';
import hasPermission from 'lib2/hasPermission';

import directory from 'api2/directory';

import LegacySidebar from 'components2/LegacySidebar';
import SpinOverlay from 'components2/SpinOverlay';
import Promocode from 'components2/Promocode';
import Balance from 'components2/Balance';
import TabLink from 'components2/TabLink';
import PaidServices from 'components2/PaidServices';

import { DoublePaymentNotify } from './DoublePaymentNotify';

import './index.css';

const b = block('balance-page');

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

        this.state = {
            busy: true,
        };

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

    componentDidMount() {
        RouteTiming.end();

        this._onBalanceStoreChange();
        this._balanceStoreListener = BalanceStore.onChange(this._onBalanceStoreChange);

        this._update();
    }

    componentWillUnmount() {
        this._unmounted = true;
        this._balanceStoreListener.remove();
    }

    _onBalanceStoreChange() {
        this.setState({
            hasContract: BalanceStore.get('has_contract'),
        });
    }

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

        Promise
            .all([
                directory.send('GET', '/v11/subscription/'),
                directory.send('GET', '/v11/subscription/pricing'),
            ])
            .then(([balance, pricing]) => {
                if (balance.ok) {
                    BalanceStore.mergeState(balance.body);
                }

                if (pricing.ok) {
                    PricingStore.mergeState(pricing.body);
                }
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({
                        busy: false,
                    });
                }
            });
    }

    render() {
        const { busy, hasContract } = this.state;

        if (busy) {
            return (
                <div className={b({}).mix(this.props.cls)}>
                    <LegacySidebar />
                    <div className={b('content')}>
                        <SpinOverlay
                            progress
                            size="m"
                            position="center"
                        />
                    </div>
                </div>
            );
        }

        if (hasContract === false) {
            return <Redirect to="/portal/balance/contract?source=balance" />;
        }

        return (
            <div className={b({}).mix(this.props.cls)}>
                <LegacySidebar />
                <div className={b('content')}>
                    <div className={b('header')}>
                        <div>
                            <h1 className={b('title')}>
                                {i18n('balance.title')}
                            </h1>
                            <Balance cls={b('balance')} />
                        </div>
                        <DoublePaymentNotify cls={b('notify')} />
                    </div>
                    <div className={b('tabs')}>
                        <TabLink.Group>
                            <TabLink url="/portal/balance">
                                {i18n('balance.services.title')}
                            </TabLink>
                        </TabLink.Group>
                        <TabLink.Pane cls={b('paid-services')}>
                            <div className={b('paid-services-content')}>
                                <PaidServices cls={b('services')} />
                                {hasPermission('activate_promocode') && (
                                    <div className={b('promo-code')}>
                                        <h3 className={b('subtitle')}>
                                            {i18n('balance.promocode.subtitle')}
                                        </h3>
                                        <Promocode />
                                    </div>
                                )}
                            </div>
                            <div className={b('pricing-info')}>
                                <h2 className={b('pricing-info-title')}>
                                    {i18n('balance.pricing_info.title')}
                                </h2>
                                <div
                                    className={b('pricing-info-content')}
                                    dangerouslySetInnerHTML={{
                                        __html: i18n('balance.pricing_info.content', {
                                            pricing_url: getHelpUrl('ui.help.billing'),
                                            payment_timeline_url: getHelpUrl('ui.help.billing_acts'),
                                            offer_url: getHelpUrl('ui.help.offer'),
                                        }),
                                    }}
                                />
                            </div>
                        </TabLink.Pane>
                    </div>
                </div>
            </div>
        );
    }
}
