import PropTypes from 'prop-types';
import React from 'react';
import Button from 'react-bem-components/lib/Button';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import Form from 'ui/Form';
import FormMixin from 'lib/FormMixin';

import userValidator from 'validation/user';
import UserActions from 'actions/User';
import UserStore from 'stores/Users';
import filterInput from './filterInput';
import Contacts from './Components/Contacts';

import './index.css';

const UpdateContacts = React.createClass({

    mixins: [FormMixin],

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

    componentWillReceiveProps() {
        this.setState(this.getInitialState());
    },

    _handleFormSubmit(data) {
        if (this._use(userValidator, filterInput)._validate(data)) {
            Metrika.send('Карточка пользователя', 'Редактирование контактов', 'Сохранить');

            return this._submit(UserActions.updateUser(data, this.props.id), {
                success: i18n('user.status.contacts_updated'),
                failure: i18n('user.status.failed_to_update_contacts'),
            });
        }
    },

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

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

                <Contacts user={user} errors={errors} />
                <Form.Error value={errors._common} mod="standalone" />

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

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

export default UpdateContacts;
