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 AuthStore from 'stores/Auth';
import departmentValidator from 'validation/department';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import Name from './Components/Name';
import Description from './Components/Description';
import Email from './Components/Email';
import Head from './Components/Head';
import Parent from './Components/Parent';

import filterInput from './filterInput';

const Create = React.createClass({

    mixins: [FormMixin],

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

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

            return this._submit(DepartmentActions.createDepartment(data), {
                success: i18n('department.status.created'),
                failure: i18n('department.status.failed_to_create'),
            });
        }
    },

    render() {
        const { parentId, onCancel } = this.props;
        const errors = this.state.errors.toJS();
        const department = DepartmentStore.get(parentId);

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

                <Name errors={errors} />
                <Description errors={errors} />
                {AuthStore.hasOwnedDomains() && <Email errors={errors} />}
                <Head />
                <Parent department={department} />
                <Form.Error value={errors._common} mod="standalone" />

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

            </Form>
        );
    },

});

Create.propTypes = {
    parentId: PropTypes.string,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
};

export default Create;
