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

const Update = 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.updateGroup(data, this.props.id), {
                success: i18n('group.status.updated'),
                failure: i18n('group.status.failed_to_update'),
            });
        }
    },

    render() {
        const { id, onCancel } = this.props;
        const errors = this.state.errors.toJS();
        const group = GroupStore.get(id);

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

                <div className="form__side-pane">
                    <Avatar group={group} />
                </div>
                <div className="form__content">
                    <Name group={group} errors={errors} />
                    <Description group={group} errors={errors} />
                    {AuthStore.hasOwnedDomains() && <Email group={group} errors={errors} />}
                    <Form.Error value={errors._common} mod="standalone" />

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

            </Form>
        );
    },

});

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

export default Update;
