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 GroupActions from 'actions/Group';
import groupValidator from 'validation/group';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';
import AuthStore from 'stores/Auth';
import Name from './Components/Name';
import Description from './Components/Description';
import Admins from './Components/Admins';
import Email from './Components/Email';

import filterInput from './filterInput';

const Create = React.createClass({

    mixins: [FormMixin],

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

    _handleFormSubmit(data) {
        if (this._use(groupValidator, filterInput)._validate(data)) {
            Metrika.send(
                'Команды', 'Форма создание команды', 'Создать',
                Metrika.getUserType()
            );

            return this._submit(GroupActions.createGroup(data), {
                success: i18n('group.status.created'),
                failure: i18n('group.status.failed_to_create'),
            });
        }
    },

    componentDidMount() {
        this._getNameRef().focus();
    },

    _setNameRef(input) {
        this._name = input;
    },

    _getNameRef() {
        return this._name;
    },

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

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

                <Name
                    errors={errors}
                    ref={this._setNameRef}
                />
                <Description errors={errors} />
                <Admins errors={errors} />
                {AuthStore.hasOwnedDomains() && <Email errors={errors} />}
                <Form.Error value={errors._common} mod="standalone" />

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

            </Form>
        );
    },

});

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

export default Create;
