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 { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import userValidator from 'validation/user';
import UserActions from 'actions/User';
import Password from './Components/Password';

import filterInput from './filterInput';

import './index.css';

const ChangePassword = 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.login_and_password_changed'),
                failure: i18n('user.status.failed_to_change_login_and_password'),
            });
        }
    },

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

        return (
            <Form
                className="change-user-password-form user-form form"
                onSubmit={this._handleFormSubmit}
                autoComplete="off"
            >

                <Password errors={errors} changeRequiredFlag />
                <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')} onClick={this.props.onCancel} />
                </Form.Buttons>
            </Form>
        );
    },

});

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

export default ChangePassword;
