import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import moment from 'moment';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import StoreMixin from 'lib/StoreMixin';
import { TRIAL_STATUS } from 'constants/Services';
import AuthStore from 'stores/Auth';

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

import Badge from './Badge';

const TRIAL_WARNING_DAYS_COUNT = 14;

const TrialBadge = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        const { serviceSlug } = this.props;

        return {
            isEnabled: AuthStore.isServiceEnabled(serviceSlug),
            trial: _.get(AuthStore.getService(serviceSlug), 'trial', null),
        };
    },

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

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

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

    render() {
        const { trial, isEnabled } = this.state;
        const { size, cls } = this.props;
        const isTrial = trial.status === TRIAL_STATUS.IN_PROGRESS;
        const isTrialWarning = trial.days_till_expiration < TRIAL_WARNING_DAYS_COUNT;

        if (!isTrial) {
            return null;
        }

        let color = 'green';
        let text = this._getText('status.free_until', {
            date: formatDate(moment(trial.expiration_date).toDate(), 'day-and-month'),
        });
        let tipHtml = this._getText('status.free_until_tip');

        if (isTrialWarning) {
            color = 'red';
        }

        if (!isEnabled) {
            color = 'grey';
        }

        const tipText = tipHtml && <span dangerouslySetInnerHTML={{ __html: tipHtml }} />;

        return <Badge cls={cls} color={color} tipText={tipText} text={text} size={size} />;
    },

});

TrialBadge.propTypes = {
    serviceSlug: PropTypes.string.isRequired,
    hidePricing: PropTypes.bool,
};

export default TrialBadge;
