import React from 'react';

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

import ResourcesStore from 'stores/Resources';
import ResourcesActions from 'actions/Resources';

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

import SuggestPicker from 'components/SuggestPicker';
import Form from 'lego-ui/Form';

import './CreateRelationForm.css';

const bCreateRelationForm = block('create-relation');

export default React.createClass({
    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const { serviceSlug, resourceId } = this.props;
        const roles = ResourcesStore.getRoles(serviceSlug, resourceId).map(item => ({
            val: item.slug,
            text: item.name,
        }));

        return {
            roles,
            role: roles[0] ? roles[0].val : null,
        };
    },

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

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

    _handlePickerChange(items) {
        const user = items[0];

        this.setState({ user, error: null });
    },

    _onSubmit(formData) {
        if (this.state.busy) {
            return;
        }

        const { serviceSlug, resourceId } = this.props;
        const data = {
            service: serviceSlug,
            resource_id: resourceId,
            object_type: 'user',
            object_id: Number(formData.user_id),
            name: formData.role,
        };

        this.setState({ busy: true });

        return ResourcesActions.createRelation(data)
            .then(response => {
                if (response && response.errors) {
                    this.setState({ error: response.errors.get('_common') });
                } else {
                    notify(this._getText('create_relation_success'), 'success');
                    this.props.onSubmit();
                }
            })
            .catch(() => {
                notify(this._getText('create_relation_error'), 'error');
            })
            .finally(() => {
                this.setState({ busy: false });
            });
    },

    _handleSelectChange(roles) {
        this.setState({ role: roles[0] });
    },

    render() {
        const { user, role, busy, roles, error } = this.state;
        const userTitle = this._getText('fields.user');
        const roleTitle = this._getText('fields.role');
        const userId = user ? user.getId() : '';

        return (
            <Form className={bCreateRelationForm.state({ busy })} onSubmit={this._onSubmit}>
                <div className={bCreateRelationForm('row')}>
                    <div
                        className={bCreateRelationForm('label', {
                            required: true,
                        })}
                    >
                        {userTitle}
                    </div>
                    <div className={bCreateRelationForm('control')}>
                        <SuggestPicker
                            suggest
                            multiple={false}
                            placeholder={this._getText('user_placeholder')}
                            onChange={this._handlePickerChange}
                            type="user"
                            value={user ? [user] : null}
                        />
                        <input type="hidden" value={userId} name="user_id" />
                    </div>
                </div>
                <div className={bCreateRelationForm('row')}>
                    <div
                        className={bCreateRelationForm('label', {
                            required: true,
                        })}
                    >
                        {roleTitle}
                    </div>
                    <div className={bCreateRelationForm('control')}>
                        <Select
                            zIndexGroupLevel={21}
                            cls={bCreateRelationForm('select')}
                            theme="normal"
                            size="m"
                            val={role}
                            name="role"
                            control
                            type="radio"
                            button={{ pin: 'brick-brick' }}
                            items={roles}
                            onChange={this._handleSelectChange}
                        />
                    </div>
                </div>
                {error && <div className={bCreateRelationForm('error')}>{error}</div>}
                <div className={bCreateRelationForm('actions')}>
                    <Button
                        theme="action"
                        view="default"
                        tone="default"
                        size="m"
                        disabled={!userId || !role}
                        type="submit"
                    >
                        {i18n('common.action.add')}
                    </Button>
                    <Button
                        theme="normal"
                        size="m"
                        onClick={this.props.onCancel}
                    >
                        {i18n('common.action.cancel')}
                    </Button>
                </div>
                <Spin progress={busy} size="m" position="center" />
            </Form>
        );
    },
});
