import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Button from 'react-bem-components/lib/Button';
import Form from 'ui/Form';
import FormMixin from 'lib/FormMixin';

import GroupStore from 'stores/Groups';
import ChunkStore from 'stores/Chunks';
import UserActions from 'actions/User';
import groupValidator from 'validation/group';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import Members from './Members';

import './index.css';

const Add = React.createClass({

    mixins: [FormMixin],

    getInitialState() {
        return {
            selectedItems: [],
            errors: groupValidator.getErrors(),
        };
    },

    componentDidMount() {
        this.refs.itemPicker.focus();
    },

    _handleFormSubmit(data) {
        const adminChunk = ChunkStore.get('users/role=admin');

        if (!adminChunk) {
            return;
        }

        if (data.selected_members) {
            data.members = JSON.parse(_.unescape(data.selected_members))
                .filter(Boolean)
                .map(item => ({ id: Number(item.id), role: 'admin' }));
            delete data.selected_members;
        }

        if (data.members) {
            Metrika.send(
                'Настройки организации', 'Администраторы',
                'Форма добавления', 'Добавить'
            );

            return this._submit(UserActions.updateUsers(data.members), {
                success: i18n('organization_admins.status.updated'),
                failure: i18n('organization_admins.status.failed_to_update'),
            }).then(this._fetchUpdates);
        }
    },

    _handleItemsChange(items) {
        this.setState({ selectedItems: items });
    },

    _fetchUpdates() {
        return UserActions.getAdminList();
    },

    render() {
        const { onCancel } = this.props;
        const { selectedItems } = this.state;

        const errors = this.state.errors.toJS();
        const empty = !selectedItems.length;

        return (
            <Form
                className="add-org-admins-form form"
                onSubmit={this._handleFormSubmit}
            >
                <div className="add-org-admins-form__intro">
                    {i18n('organization_admins.description.new_admins')}
                </div>
                <Members
                    ref="itemPicker"
                    group={GroupStore.getAdminGroup()}
                    errors={errors}
                    onChange={this._handleItemsChange}
                />
                <div className="add-org-admins-form__tip">
                    {i18n('organization_admins.description.suggest_tip')}
                </div>
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons mod="aligned">
                    <Button
                        text={i18n('common.action.add')}
                        type="submit"
                        disabled={empty}
                        view="action"
                    />
                    <Button
                        text={i18n('common.action.cancel')}
                        onClick={onCancel}
                    />
                </Form.Buttons>

            </Form>
        );
    },

});

Add.propTypes = {
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default Add;
