import React from 'react';

import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import { Link, Icon } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';

import ModalActions from 'actions/Modal';
import ResourcesActions from 'actions/Resources';
import ResourcesStore from 'stores/Resources';
import ConfigStore from 'stores/Config';
import PermissionStore from 'stores/Permissions';

import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import notify from 'services/notify';

import { LeftArrow } from 'components/Icon';
import NavLink from 'components/NavLink';

import './index.css';

const bResource = block('resource-page');

export default React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        let { name, description, serviceSlug } = this.props;
        let editable = PermissionStore.allowsServiceDataUpdate(serviceSlug);

        return {
            name,
            description,
            editable,
        };
    },

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

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

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

    _confirmResourceRemoval() {
        ModalActions.confirm({
            title: this._getText('remove_resource'),
            message: this._getText('remove_resource_warning'),
            onConfirm: this._removeResource,
            confirmButtonText: i18n('common.action.confirm'),
            rejectButtonText: i18n('common.action.cancel'),
        });
    },

    _removeResource() {
        const { serviceSlug, resourceId } = this.props;

        const data = {
            service: serviceSlug,
            resource_id: resourceId,
        };

        ResourcesActions.remove(data)
            .then(response => {
                if (response && response.errors) {
                    notify(response.errors.get('_common'), 'error');
                } else {
                    notify(this._getText('remove_resource_success'), 'success');
                    Url.open(Url.getServiceSettingsUrl(serviceSlug));
                }
            })
            .catch(() => {
                notify(this._getText('remove_resource_error'), 'error');
            });
    },

    render() {
        let { serviceSlug, resourceId, title, actions, hard } = this.props;
        let { name, description, editable } = this.state;

        const goUrl = ConfigStore.get(`ui.relatedResources.${serviceSlug}`, {
            tld: ConfigStore.get('app.tld'),
            id: resourceId,
        });

        let defaultName;

        if (!name) {
            defaultName = i18n(`service_page.${serviceSlug}.default_name`, { id: resourceId }) ||
                i18n('service_page.default.default_name', { id: resourceId });
        }

        if (!actions) {
            actions = [
                goUrl && (
                    <NavLink
                        theme="normal"
                        url={goUrl}
                        text={this._getText('go')}
                        cls={bResource('go')}
                        key="go"
                    />
                ),
                editable && (
                    <Link
                        theme="black"
                        text={this._getText('remove_resource')}
                        onClick={this._confirmResourceRemoval}
                        key="remove_resource"
                    />
                ),
            ];
        }

        return (
            <div className={bResource('header')}>
                <div className={bResource('actions')}>
                    <NavLink
                        hard={hard}
                        theme="black"
                        url={Url.getServiceSettingsUrl(serviceSlug)}
                    >
                        <Icon
                            cls={bResource('back')}
                            glyph="yes"
                        >
                            <LeftArrow />
                        </Icon>
                        {this._getText('back')}
                    </NavLink>
                    <span className="spacer" />
                    {actions}
                </div>
                <div className={bResource('title')}>
                    {title || name || defaultName}
                </div>
                <div className={bResource('description')}>
                    {description}
                    {!defaultName && description &&
                        <span className={bResource('description-delimiter')}>•</span>}
                    {!defaultName && resourceId}
                </div>
            </div>
        );
    },

});
