import React from 'react';
import block from 'bem-cn';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import { Button, Spin } from 'lego-on-react';
import ConfigStore from 'stores/Config';

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

import OrgProfileActions from 'actions/OrgProfile';

const b = block('remove-org');

const Remove = React.createClass({

    mixins: [PureRenderMixin],

    getInitialState() {
        return { error: null };
    },

    componentWillUnmount() {
        this._unmounted = true;
    },

    _removeOrganization() {
        const { orgId } = this.props;

        this.setState({ busy: true });

        OrgProfileActions.remove({ id: orgId })
            .then(response => {
                if (response && response.errors) {
                    this.setState({ error: response.errors.get('_common') });

                    return;
                }

                Url.open(Url.getLocation(ConfigStore.get('ui.mainPage')));
            })
            .finally(() => {
                if (!this._unmounted) {
                    this.setState({ busy: false });
                }
            });
    },

    render() {
        const { title, onCancel } = this.props;
        const { error, busy } = this.state;

        return (
            <div className={b()}>
                <h3 className={b('title')}>
                    {title}
                </h3>
                {i18n('organization_profile.delete_org_popup.message.allowed')}
                <div className={b('error')}>
                    {error}
                </div>
                <div className={b('controls')}>
                    <Button
                        cls={b('button', { type: 'cancel' })}
                        theme="normal"
                        size="m"
                        text={error ?
                            i18n('organization_profile.delete_org_popup.button.got_it') :
                            i18n('common.action.cancel')}
                        onClick={onCancel}
                    />
                    {!error &&
                    <Button
                        cls={b('button', { type: 'submit' })}
                        theme="action"
                        size="m"
                        text={i18n('organization_profile.delete_org_popup.button.delete')}
                        onClick={this._removeOrganization}
                    />}
                </div>
                <div className={b('spin', { progress: busy })}>
                    <Spin
                        progress={busy}
                        size="m"
                        position="center"
                    />
                </div>
            </div>
        );
    },

});

export default Remove;
