import React from 'react';
import _ from 'lodash';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import StoreMixin from 'lib/StoreMixin';

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

import Tabs from 'lego-ui/Tabs';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import Main from 'components/Main';
import ServiceHeader from 'components/ServiceHeader';
import ServicePlan from 'components/ServicePlan';

import ServiceDetails from 'components/ServiceDetails';
import LicensesList from './LicensesList';
import RequestsList from './RequestsList';

import './index.css';

const DEFAULT_TAB_ID = 'licenses';

const bSubscriptionService = block('subscription-service');

export default React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const nextState = {};

        if (this.state && this.state.serviceSlug) {
            nextState.serviceSlug = this.state.serviceSlug;
        }

        if (!nextState.serviceSlug) {
            nextState.serviceSlug = this.props.serviceSlug || this.props.params.serviceSlug;
        }

        nextState.isEnabled = AuthStore.isServiceEnabled(nextState.serviceSlug);
        nextState.requestsCount = LicenseStore.getRequestsCount(nextState.serviceSlug);
        nextState.selectedTabId = _.get(this.state, 'selectedTabId', DEFAULT_TAB_ID);

        return nextState;
    },

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

        if (Url.getQueryParam('from') === 'agreement' && Url.getQueryParam('section') === 'requests') {
            this.setState({
                selectedTabId: 'requests',
            });
        }
    },

    componentDidUpdate(prevProps) {
        let serviceSlug = this.props.serviceSlug || this.props.params.serviceSlug;
        let prevServiceSlug = prevProps.serviceSlug || prevProps.params.serviceSlug;

        if (serviceSlug !== prevServiceSlug) {
            this.setState({ serviceSlug });
        }
    },

    _handleTabChange(tabId) {
        this.setState({
            selectedTabId: tabId === 'settings' ? DEFAULT_TAB_ID : tabId,
        });
    },

    _getRequestsTitle() {
        const title = i18n('license_requests.tab_title');
        const { requestsCount } = this.state;

        if (requestsCount > 0) {
            return (
                <span>
                    {title}
                    &nbsp;
                    <span className={bSubscriptionService('counter')}>{requestsCount}</span>
                </span>
            );
        }

        return title;
    },

    render() {
        const { selectedTabId, isEnabled, serviceSlug } = this.state;
        const settingsUrl = ConfigStore.get(`ui.settings.${serviceSlug}`, {
            tld: ConfigStore.get('app.tld'),
        });

        const shouldRenderRequests = !AuthStore.isPartnerOrganization() &&
            serviceSlug === 'tracker';

        const tabs = {
            licenses: (
                <Tabs.Item id="licenses" title={i18n('licenses.tabs.subscriptions')}>
                    <LicensesList serviceSlug={serviceSlug} />
                </Tabs.Item>
            ),
            requests: shouldRenderRequests && (
                <Tabs.Item id="requests" title={this._getRequestsTitle()}>
                    <RequestsList serviceSlug={serviceSlug} />
                </Tabs.Item>
            ),
            settings: settingsUrl && (
                <Tabs.Item
                    id="settings"
                    url={settingsUrl}
                    title={i18n('licenses.tabs.settings')}
                />
            ),
        };

        const detailsTitle = i18n(`service_page.${serviceSlug}.plan.title`) ||
            i18n('service_page.default.plan.title');

        return (
            <Main cls={bSubscriptionService()} key={serviceSlug}>
                <ServiceHeader
                    serviceSlug={serviceSlug}
                    showBadge
                    hideMainAction={serviceSlug === 'disk'}
                />
                {!AuthStore.isPartnerOrganization() &&
                <ServiceDetails>
                    <ServiceDetails.Item title={detailsTitle}>
                        <ServicePlan serviceSlug={serviceSlug} />
                    </ServiceDetails.Item>
                </ServiceDetails>}
                {isEnabled &&
                <Tabs selectedTabId={selectedTabId} onChange={this._handleTabChange}>
                    {tabs.licenses}
                    {tabs.requests}
                    {tabs.settings}
                </Tabs>}
            </Main>
        );
    },
});
