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 DepartmentStore from 'stores/Departments';
import departmentValidator from 'validation/department';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import filterInput from './filterInput';
import Parent from './Components/Parent';

const Move = React.createClass({

    mixins: [FormMixin],

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

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

            return this._submit(DepartmentActions.updateDepartment(data, this.props.id), {
                success: i18n('department.status.moved'),
                failure: i18n('department.status.failed_to_move'),
            });
        }
    },

    render() {
        const { id } = this.props;
        const errors = this.state.errors.toJS();

        const department = DepartmentStore.get(id);
        const parent = department ? department.getParent() : null;

        return (
            <Form
                className="move-department-form form"
                onSubmit={this._handleFormSubmit}
            >

                <Parent department={parent} />
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons>
                    <Button
                        text={i18n('department.action.save_changes')}
                        type="submit"
                        view="action"
                        size="l"
                        width="available"
                    />
                </Form.Buttons>

            </Form>
        );
    },

});

Move.propTypes = {
    id: PropTypes.string,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default Move;
