import React from 'react';

import { block } from 'bem-cn';
import { Spin, Link } from 'lego-on-react';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import SubscriptionActions from 'actions/Subscription';
import ServiceActions from 'actions/Services';
import { SERVICES_WITH_LICENSES, SERVICES_IN_BETA } from 'constants/Services';

import ResourcesStore from 'stores/Resources';
import PermissionStore from 'stores/Permissions';
import DomainStore from 'stores/Domains';

import notify from 'services/notify';
import { i18n, pluralize } from 'lib/i18n';
import StoreMixin from 'lib/StoreMixin';
import { Gear, Beta, ServiceIcon } from 'components/Icon';
import NavLink from 'components/NavLink';

import ServiceBadge from 'components/ServiceBadge';

import './Card.css';

const bDashboardItem = block('dashboard-item');

const Card = React.createClass({

    mixins: [PureRenderMixin, StoreMixin],

    getStoreState() {
        let nextState = { resourceCounter: ResourcesStore.getCount(this.props.id) };

        if (!this.state || this.state.loading === undefined) {
            nextState.loading = !this.props.ready;
        }

        return nextState;
    },

    componentDidMount() {
        this.subscribe([ResourcesStore, PermissionStore,
            // ResourcesStore.getCount() для serviceSlug ==='webmaster' берет данные из DomainStore
            DomainStore]);
    },

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.ready !== this.props.ready || prevState.loading === prevProps.ready) {
            this.setState({ loading: !this.props.ready });
        }
    },

    _enableService() {
        let serviceSlug = this.props.id;

        return ServiceActions.toggle({
            serviceSlug,
            isEnabled: false,
            onSubmit: this._onToggleSubmit,
        });
    },

    _onToggleSubmit(params) {
        if (this.state.loading) {
            return;
        }

        let service = this.props.id;

        this.setState({ loading: true });

        SubscriptionActions.toggleService(service, true, params)
            .then(response => {
                if (response && response.errors) {
                    notify(response.errors.get('_common'), 'error');
                }
            })
            .catch(() => {
                notify(i18n('service_subscription.common.status.failed_to_enable'), 'error');
            });
    },

    render() {
        const itemProps = this.props;
        const id = itemProps.id;

        let settingsLink = itemProps.settingsLink &&
            <NavLink url={itemProps.settingsLink} cls={bDashboardItem('configure')} theme="normal">
                <Gear className={bDashboardItem('configure-icon')} />
            </NavLink>;
        let counter;
        let action;

        if (this.state.loading) {
            action = (
                <div className={bDashboardItem('action', { process: true })}>
                    <Spin size="xxs" progress />
                    {i18n('dashboard.enabling')}
                </div>
            );
        } else if (itemProps.canBeEnabled && !itemProps.active) {
            action = (
                <Link cls={bDashboardItem('action')} theme="normal" onClick={this._enableService}>
                    {i18n('dashboard.enable')}
                </Link>
            );
        } else if (itemProps.action && itemProps.actionLink) {
            action = (
                <NavLink cls={bDashboardItem('action')} theme="normal" url={itemProps.actionLink}>
                    {itemProps.action}
                </NavLink>
            );
        }

        const resourceCount = this.state.resourceCounter;

        if (resourceCount) {
            counter = (
                <NavLink theme="normal" url={itemProps.settingsLink} cls={bDashboardItem('counter')}>
                    {pluralize(resourceCount, i18n(`services.${id}.counter`) || i18n('services.default.counter'))}
                </NavLink>
            );
        }

        return (
            <div
                className={bDashboardItem({
                    featured: itemProps.featured,
                    'with-counter': Boolean(resourceCount),
                })}
                data-id={id}
            >
                <div className={bDashboardItem('frame')}>
                    <NavLink
                        cls={bDashboardItem('link')}
                        url={itemProps.url}
                        metrika={['Дэшборд', itemProps.metrika]}
                        theme="normal"
                    />
                    {settingsLink}
                    <div className={bDashboardItem('header')}>
                        <ServiceIcon
                            cls={bDashboardItem('icon')}
                            serviceSlug={id}
                        />
                        <div className={bDashboardItem('title')}>
                            <span className={bDashboardItem('name')}>
                                {itemProps.title}
                                {SERVICES_IN_BETA.indexOf(id) !== -1 &&
                                <Beta width="15" height="15" cls={bDashboardItem('beta-badge')} />}
                            </span>
                            {SERVICES_WITH_LICENSES.indexOf(id) !== -1 &&
                            <ServiceBadge serviceSlug={id} cls={bDashboardItem('badge')} />}
                        </div>
                    </div>
                    <div className={bDashboardItem('content')}>
                        {itemProps.text}
                    </div>
                    <div className={bDashboardItem('footer')}>
                        {counter}
                        {action}
                    </div>
                </div>
            </div>
        );
    },
});

export default Card;
