import React from 'react';
import { Button } from 'lego-on-react';
import { block } from 'bem-cn';
import Modal from 'components2/Modal';
import { PricingStore, ConfigStore } from 'lib2/stores';
import getService from 'lib2/getService';
import TrialStatus from 'const2/TrialStatus';
import { i18n, pluralize, formatDate } from 'i18n2';

import './SubscriptionService.css';

const b = block('subscription-service-toggle');

const MONTHS_TILL_TRIAL_EXPIRATION = 1;
const DATA_PURGE_DELAY = 30; // days

const NonTerminalStatuses = [
    null,
    undefined,
    TrialStatus.NOT_STARTED,
    TrialStatus.IN_PROGRESS,
];

function formatTrialExpirationDate(date) {
    if (!date) {
        date = new Date();
        date.setMonth(date.getMonth() + MONTHS_TILL_TRIAL_EXPIRATION);
    }

    return formatDate(date, 'short');
}

function addDays(date, days) {
    let outputDate = new Date(date);

    outputDate.setDate(outputDate.getDate() + days);

    return outputDate;
}

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

        let { serviceSlug } = props;
        let { trial } = getService(serviceSlug);

        this.state = {
            trialStatus: trial.status,
            trialExpirationDate: trial.expiration_date,
            userCount: PricingStore.get(['services', serviceSlug, 'users_count']),
        };

        this._onConfirm = this._onConfirm.bind(this);
        this._onConfirmWithoutLicenses = this._onConfirmWithoutLicenses.bind(this);
    }

    _getText(key, params) {
        let { serviceSlug } = this.props;

        return i18n(`service_page.${serviceSlug}.${key}`, params) ||
            i18n(`service_page.default.${key}`, params);
    }

    _getBodyContent() {
        let { trialStatus, trialExpirationDate, userCount } = this.state;
        let { serviceSlug, targetStatus } = this.props;

        if (targetStatus === false) {
            if (trialStatus === TrialStatus.IN_PROGRESS) {
                return this._getText('disable.trial.in_progress', {
                    trial_expiration_date: formatTrialExpirationDate(trialExpirationDate),
                    data_purge_date: formatDate(addDays(trialExpirationDate, DATA_PURGE_DELAY), 'short'),
                });
            }

            return this._getText('disable.trial.expired', {
                trial_expiration_date: formatTrialExpirationDate(trialExpirationDate),
                data_purge_date: formatDate(addDays(Date.now(), DATA_PURGE_DELAY), 'short'),
            });
        }

        if (NonTerminalStatuses.includes(trialStatus)) {
            return this._getText('enable.trial.unexpired', {
                trial_expiration_date: formatTrialExpirationDate(trialExpirationDate),
                pricing_link_url: ConfigStore.get(`ui.about.${serviceSlug}`),
                pricing_link_class: 'link link_theme_normal link_external',
                pricing_link_target: '_blank',
            });
        }

        if (userCount) {
            return this._getText('enable.trial.expired.with_subscriptions', {
                n_subscriptions: pluralize(
                    userCount,
                    i18n('licenses.count_subscriptions')
                ),
            });
        }

        return this._getText('enable.trial.expired.without_subscriptions');
    }

    _onConfirm() {
        this.props.onConfirm();
    }

    _onConfirmWithoutLicenses() {
        this.props.onConfirm({ drop_licenses: true });
    }

    _getActions() {
        let { trialStatus, userCount } = this.state;
        let { targetStatus, onCancel } = this.props;

        if (targetStatus === false) {
            return (
                <Modal.ConfirmActions
                    onConfirm={this._onConfirm}
                    onCancel={onCancel}
                    confirmCaption={this._getText('action.disable')}
                />
            );
        }

        if (NonTerminalStatuses.includes(trialStatus) || (!userCount && trialStatus === TrialStatus.EXPIRED)) {
            return (
                <Modal.ConfirmActions
                    onConfirm={this._onConfirm}
                    onCancel={onCancel}
                    confirmCaption={this._getText('action.enable')}
                />
            );
        }

        return (
            <Modal.RightActions>
                <Button
                    cls={b('button', { type: 'cancel' })}
                    text={i18n('common.action.cancel')}
                    theme="normal"
                    size="m"
                    onClick={onCancel}
                />
                <Button
                    cls={b('button', { type: 'enable_without_subs' })}
                    text={this._getText('action.enable_without_subscriptions')}
                    theme="normal"
                    size="m"
                    onClick={this._onConfirmWithoutLicenses}
                />
                <Button
                    cls={b('button', { type: 'enable_with_subs' })}
                    text={this._getText('action.enable_with_subscriptions')}
                    theme="action"
                    size="m"
                    controlAttrs={{
                        autoFocus: 'yes',
                    }}
                    onClick={this._onConfirm}
                />
            </Modal.RightActions>
        );
    }

    render() {
        let { targetStatus, onCancel, visible } = this.props;

        return (
            <Modal
                cls={b()}
                visible={visible}
            >
                <Modal.Title>
                    {this._getText(`${targetStatus ? 'enable' : 'disable'}.title`)}
                </Modal.Title>
                <Modal.CloseButton onClick={onCancel} />
                <Modal.Body>
                    <div
                        className={b('content')}
                        dangerouslySetInnerHTML={{ __html: this._getBodyContent() }}
                    />
                </Modal.Body>
                {this._getActions()}
            </Modal>
        );
    }
}
