import React from 'react';
import { Button } from 'lego-on-react';
import { block } from 'bem-cn';
import { BalanceStore } from 'lib2/stores';
import hasPermission from 'lib2/hasPermission';
import directory from 'api2/directory';
import { i18n, formatCurrency, formatDate } from 'i18n2';

import './index.css';

const WARNING_PERIOD = 14; // days

const b = block('debt-notification');

function toDate(date) {
    return date instanceof Date ? date : new Date(date);
}

export default class extends React.PureComponent {
    constructor() {
        super();
        this.state = {};

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

    componentDidMount() {
        this._update();
        this._balanceStoreListener = BalanceStore.onChange(this._update);

        if (BalanceStore.get('balance') === undefined) {
            directory.send('GET', '/v11/subscription/').then(({ body }) => {
                BalanceStore.mergeState(body);
            });
        }
    }

    componentWillUnmount() {
        this._balanceStoreListener.remove();
    }

    _update() {
        let {
            balance,
            payment_due_date: paymentDueDate,
            debt_start_date: debtStartDate,
            days_until_disable_by_debt: daysTillBlocked,
        } = BalanceStore.getState();

        this.setState({
            balance,
            paymentDueDate,
            debtStartDate,
            daysTillBlocked,
        });
    }

    _shouldRender() {
        if (!hasPermission('can_pay')) {
            return false;
        }

        let { balance, paymentDueDate, debtStartDate } = this.state;

        if (balance === null || balance === undefined || balance >= 0 || !paymentDueDate) {
            return false;
        }

        if (!debtStartDate || Date.now() < toDate(debtStartDate).getTime()) {
            return false;
        }

        return true;
    }

    _isBlocked() {
        return this.state.daysTillBlocked === 0;
    }

    _isWarning() {
        const { daysTillBlocked } = this.state;

        return typeof daysTillBlocked === 'number' && daysTillBlocked <= WARNING_PERIOD;
    }

    render() {
        if (!this._shouldRender()) {
            return null;
        }

        let { balance, paymentDueDate } = this.state;
        let type = this._isBlocked() ? 'blocked' : 'will_block';

        let content = i18n(`balance.notification.${type}.description`, {
            amount: formatCurrency(balance, 'RUB'),
            date: formatDate(paymentDueDate, 'short'),
        });

        return (
            <div className={b({ warning: this._isWarning() })}>
                <div className={b('content')}>
                    <h2 className={b('title')}>
                        {i18n(`balance.notification.${type}.title`, {
                            date: formatDate(paymentDueDate, 'short'),
                        })}
                    </h2>
                    <div
                        className={b('description')}
                        dangerouslySetInnerHTML={{ __html: content }}
                    />
                </div>
                <div className={b('options')}>
                    <Button
                        theme="normal"
                        type="link"
                        size="s"
                        cls={b('button', { role: 'pay' })}
                        url="/portal/balance"
                    >
                        {i18n('balance.notification.pay_button')}
                    </Button>
                </div>
            </div>
        );
    }
}
