import _ from 'lodash';
import React from 'react';
import moment from 'moment';
import { block } from 'bem-cn';
import PropTypes from 'prop-types';
import { Button, Link } from 'lego-on-react';
import { TRIAL_STATUS } from 'constants/Services';

import StoreMixin from 'lib/StoreMixin';

import AuthStore from 'stores/Auth';
import SubscriptionStore from 'stores/Subscription';
import OrganizationStore from 'stores/Organizations';
import ConfigStore from 'stores/Config';

import { i18n, pluralize, formatDate } from 'lib/i18n';

import './index.css';

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

const DAYS_TO_REMOVE_DATA = 30;
const MONTHS_TO_TRIAL_END = 1;

/*
const stub = {
    offTrialNotStatred: {
        trialStatus: TRIAL_STATUS.NOT_STARTED,
        isEnabled: false,
        usersCount: 0,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    },
    offTrialInProgress: {
        trialStatus: TRIAL_STATUS.IN_PROGRESS,
        isEnabled: false,
        usersCount: 0,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    },
    offTrialExpired: {
        trialStatus: TRIAL_STATUS.EXPIRED,
        isEnabled: false,
        usersCount: 0,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    },
    offTrialExpiredWithLicenses: {
        trialStatus: TRIAL_STATUS.EXPIRED,
        isEnabled: false,
        usersCount: 5,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    },
    onTrialInProgress: {
        trialStatus: TRIAL_STATUS.IN_PROGRESS,
        isEnabled: true,
        usersCount: 0,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    },
    onTrialExpired: {
        trialStatus: TRIAL_STATUS.EXPIRED,
        isEnabled: true,
        usersCount: 0,
        trialExpirationDate: undefined,
        trialDaysLeft: undefined
    }
};
*/

const SubscriptionServiceToggle = React.createClass({
    mixins: [StoreMixin],

    getStoreState() {
        const { serviceSlug } = this.props;
        const serviceData = AuthStore.getService(serviceSlug) || {};
        const { trial: trialData } = serviceData;

        // return stub.offTrialExpiredWithLicenses;

        return {
            trialStatus: AuthStore.getServiceTrialStatus(serviceSlug),
            isEnabled: AuthStore.isServiceEnabled(serviceSlug),
            usersCount: SubscriptionStore.getPricing(serviceSlug).users_count,
            trialExpirationDate: _.get(trialData, 'expiration_date'),
            trialDaysLeft: _.get(trialData, 'days_till_expiration'),
        };
    },

    componentDidMount() {
        this.subscribe([AuthStore, OrganizationStore, SubscriptionStore]);
    },

    _getTrialLastDayDate(trialExpirationDate) {
        const date = trialExpirationDate ? moment(trialExpirationDate) : moment().add(MONTHS_TO_TRIAL_END, 'months');

        return formatDate(date, 'day-and-month');
    },

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

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

    _getContent() {
        const { isEnabled, trialStatus, usersCount, trialExpirationDate } = this.state;

        if (isEnabled) {
            const isTrialInProgress = trialStatus === TRIAL_STATUS.IN_PROGRESS;
            const dateRemoveData = moment(isTrialInProgress ? trialExpirationDate : undefined)
                .add(DAYS_TO_REMOVE_DATA, 'day');
            const descriptionKey = isTrialInProgress ? 'in_trial' : 'after_trial';

            return (
                <div className={bSubscriptionServiceToggle('content')}>
                    <p className={bSubscriptionServiceToggle('description')}>
                        {this._getText(`description.on.${descriptionKey}`, {
                            date: this._getTrialLastDayDate(trialExpirationDate),
                        })}
                    </p>
                    <p className={bSubscriptionServiceToggle('warning')}>
                        {this._getText('warning_remove_date', {
                            date: formatDate(dateRemoveData, 'day-and-month'),
                        })}
                    </p>
                </div>
            );
        }

        if (trialStatus === TRIAL_STATUS.NOT_STARTED || trialStatus === TRIAL_STATUS.IN_PROGRESS) {
            return (
                <div className={bSubscriptionServiceToggle('content')}>
                    <div className={bSubscriptionServiceToggle('description', { role: 'person' })}>
                        <p className={bSubscriptionServiceToggle('description')}>
                            {this._getText('description.off.trial_in_progress_1', {
                                date: this._getTrialLastDayDate(trialExpirationDate),
                            })}
                        </p>
                        <p className={bSubscriptionServiceToggle('description')}>
                            {this._getText('description.off.trial_in_progress_2')}
                        </p>
                        <Link
                            cls={bSubscriptionServiceToggle('link-about')}
                            theme="normal"
                            url={ConfigStore.get(`ui.about.${this.props.serviceSlug}`)}
                            text={this._getText('more')}
                            target="_blank"
                        />
                    </div>
                </div>
            );
        }

        let personText = this._getText('description.off.with_subs.person', {
            n_subs: pluralize(
                usersCount,
                i18n('service_page.default.plan.count_subscriptions')
            ),
        });
        let priceHtml = this._getText('description.off.with_subs.price');

        if (!usersCount) {
            personText = this._getText('description.off.without_subs.person');
            priceHtml = this._getText('description.off.without_subs.price');
        }

        return (
            <div className={bSubscriptionServiceToggle('content')}>
                <div className={bSubscriptionServiceToggle('description', { role: 'person' })}>
                    {personText}
                </div>
                <div
                    className={bSubscriptionServiceToggle('description', { role: 'price' })}
                    dangerouslySetInnerHTML={{ __html: priceHtml }}
                />
            </div>
        );
    },

    _getActions() {
        const { isEnabled, trialStatus, usersCount } = this.state;

        if (isEnabled) {
            return (
                <div className={bSubscriptionServiceToggle('actions')}>
                    <Button
                        text={this._getText('disable')}
                        theme="action"
                        size="m"
                        controlAttrs={{
                            autoFocus: 'yes',
                        }}
                        onClick={() => this.props.onConfirm()}
                    />
                </div>
            );
        }

        if (trialStatus === TRIAL_STATUS.NOT_STARTED || trialStatus === TRIAL_STATUS.IN_PROGRESS ||
            (!usersCount && trialStatus === TRIAL_STATUS.EXPIRED)) {
            return (
                <div className={bSubscriptionServiceToggle('actions')}>
                    <Button
                        text={this._getText('enable')}
                        theme="action"
                        size="m"
                        controlAttrs={{
                            autoFocus: 'yes',
                        }}
                        onClick={() => this.props.onConfirm()}
                    />
                </div>
            );
        }

        return (
            <div className={bSubscriptionServiceToggle('actions')}>
                <Button
                    text={this._getText('enable_with_subs')}
                    theme="action"
                    size="m"
                    controlAttrs={{
                        autoFocus: 'yes',
                    }}
                    onClick={() => this.props.onConfirm()}
                />
                <Button
                    text={this._getText('enable_without_subs')}
                    size="m"
                    theme="normal"
                    onClick={() => this.props.onConfirm({ drop_licenses: true })}
                />
            </div>
        );
    },

    render() {
        return (
            <div className={bSubscriptionServiceToggle()}>
                {this._getContent()}
                {this._getActions()}
            </div>
        );
    },
});

SubscriptionServiceToggle.propTypes = {
    serviceSlug: PropTypes.string.isRequired,
};

export default SubscriptionServiceToggle;
