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 DepartmentActions from 'actions/Department';
import departmentValidator from 'validation/department';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import filterInput from './filterInput';
import Members from './Components/Members';

import './index.css';

const AddMembers = React.createClass({

    mixins: [FormMixin],

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

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

    _handleFormSubmit(data) {
        if (data.members) {
            data.members = JSON.parse(_.unescape(data.members));
        }

        if (this._use(departmentValidator, filterInput)._validate(data)) {
            Metrika.send('Структура', 'Форма перемещения сотрудников', 'Переместить');

            return this._submit(DepartmentActions.addMembers(data, this.props.id), {
                success: i18n('department.status.members_updated'),
                failure: i18n('department.status.failed_to_update_members'),
            });
        }
    },

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

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

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

        return (
            <Form
                className={`add-${type}-form form`}
                title={this.props.title}
                onSubmit={this._handleFormSubmit}
            >

                <input type="hidden" name="department_id" value={this.props.id} />

                <Members
                    ref="itemPicker"
                    type={type}
                    multiple={multiple}
                    errors={errors}
                    onChange={this._handleItemsChange}
                />
                <Form.Error value={errors._common} mod="standalone" />

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

            </Form>
        );
    },

});

AddMembers.propTypes = {
    id: PropTypes.string,
    type: PropTypes.oneOf(['users', 'departments']),
    multiple: PropTypes.bool,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default AddMembers;
