import React from 'react';
import { block } from 'bem-cn';
import { Button } from 'lego-on-react';
import { i18n, formatCurrency, formatDate } from 'i18n2';

import { BalanceStore } from 'lib2/stores';
import hasPermission from 'lib2/hasPermission';
import openUrl from 'lib2/openUrl';
import BalancePolling from 'lib2/BalancePolling';

import Payment from 'components2/Payment';
import PricingDetails from 'components2/PricingDetails';

import './index.css';

const b = block('balance');

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

        this.state = {};

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

    componentDidMount() {
        this._onBalanceStoreChange();
        this._balanceStoreListener = BalanceStore.onChange(this._onBalanceStoreChange);
    }

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

    _onPaymentSuccess() {
        BalancePolling.start();
    }

    _onBalanceStoreChange() {
        const {
            balance,
            payment_due_date: paymentDueDate,
            has_contract: hasContract,
            next_act_date: nextActDate,
            person_type: personType,
        } = BalanceStore.getState();

        this.setState({
            balance: balance || 0,
            paymentDueDate,
            hasContract,
            nextActDate,
            personType,
        });

        if (balance !== undefined && this.state.amount === undefined) {
            this.setState({
                amount: balance < 0 ? String(-balance) : '',
            });
        }
    }

    _onCreateContractClick() {
        openUrl('/portal/balance/contract?source=balance');
    }

    render() {
        const { busy, amount, balance, paymentDueDate, hasContract, nextActDate, personType } = this.state;
        const isNegative = balance < 0;

        return (
            <div className={b({}).mix(this.props.cls)}>
                <PricingDetails
                    cls={b('details')}
                    busy={busy}
                >
                    <PricingDetails.Slot label={i18n('balance.details.current')}>
                        <span
                            className={b('value', { negative: isNegative })}
                            dangerouslySetInnerHTML={{ __html: formatCurrency(balance, 'RUB') }}
                        />
                    </PricingDetails.Slot>
                    {hasContract && (
                        <PricingDetails.Slot
                            label={i18n('balance.details.next_act')}
                            htmlTip={i18n('balance.services.description', {
                                chargeoff_date: formatDate(nextActDate),
                            })}
                        >
                            {formatDate(nextActDate, 'short')}
                        </PricingDetails.Slot>
                    )}
                </PricingDetails>
                <div className={b('payment')}>
                    {isNegative && paymentDueDate && (
                        <div
                            className={b('description')}
                            dangerouslySetInnerHTML={{
                                __html: i18n('subscription.balance.description.negative_amount', {
                                    date: formatDate(paymentDueDate),
                                }),
                            }}
                        />
                    )}
                    {hasPermission('can_pay') && hasContract && (
                        <Payment
                            cls={b('payment')}
                            personType={personType}
                            onSuccess={this._onPaymentSuccess}
                            amount={amount}
                        />
                    )}
                    {hasPermission('can_pay') && hasContract === false && (
                        <div className={b('agreement')}>
                            <div className={b('description')}>
                                {i18n('balance.no_contract.notification')}
                            </div>
                            <Button
                                cls={b('button', { role: 'agreement' })}
                                text={i18n('balance.no_contract.create')}
                                onClick={this._onCreateContractClick}
                                theme="action"
                                size="m"
                            />
                        </div>
                    )}
                </div>
            </div>
        );
    }
}
