import PropTypes from 'prop-types';
import React from 'react';
import classSet from 'classnames';

import { Button } from 'lego-on-react';
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 DepartmentStore from 'stores/Departments';
import Identity from './Components/Identity';
import Login from './Components/Login';
import Password from './Components/Password';
import Contacts from './Components/Contacts';
import Department from './Components/Department';

import filterInput from './filterInput';

import './index.css';

const Create = React.createClass({

    mixins: [FormMixin],

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

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

    _handleFormSubmit(data) {
        const { sameNicknameDismissed, nickname } = this.state;

        if (this._use(userValidator, filterInput)._validate(data)) {
            const isDismissionChecked = sameNicknameDismissed !== undefined && data.nickname === nickname;

            // проверяем, занят ли логин другим неуволенным пользователем;
            // если не занят, проверяем, был ли такой логин раньше уволен,
            // если эта проверка еще не была сделана;
            // если логин занят, опускаем проверку, был ли такой логин раньше уволен
            return UserActions.isUsed(data.nickname)
                .then(isUsed => {
                    if (!isUsed && !isDismissionChecked) {
                        return UserActions.isDismissed(data.nickname);
                    }
                })
                .then(isDismissed => isDismissed ||
                    this._pushData(data).then(response => response && response.errors ? undefined : isDismissed))
                .then(isDismissed => {
                    if (isDismissed !== false) {
                        this.setState({
                            sameNicknameDismissed: isDismissed,
                            nickname: data.nickname,
                        });

                        return;
                    }

                    Metrika.reachGoal('AddUser');

                    if (this.props.onSubmit) {
                        this.props.onSubmit(data);
                    }
                });
        }
    },

    _pushData(data) {
        const { redirect, notifications } = this.props;
        let options;

        if (notifications !== false) {
            options = {
                success: i18n('user.status.created'),
                failure: i18n('user.status.failed_to_create'),
            };
        }

        Metrika.send('Структура', 'Форма создание пользователя', 'Создать');

        return this._submit(UserActions.createUser(data, redirect !== false), options || {});
    },

    _cancel() {
        const { onCancel } = this.props;

        if (this.state.sameNicknameDismissed) {
            this.setState(this.getInitialState());
        } else if (onCancel) {
            onCancel();
        }
    },

    _renderNicknameReuseWarning() {
        const content = i18n('user.warning.nickname_reuse', {
            nickname: this.state.nickname,
        });

        return (
            <div
                className="user-nickname-reuse__warning"
                dangerouslySetInnerHTML={{ __html: content }}
            />
        );
    },

    render() {
        const { departmentId, removeCancelButton, submitButtonText } = this.props;
        const { sameNicknameDismissed } = this.state;

        const department = DepartmentStore.get(departmentId);
        const errors = this.state.errors.toJS();

        const className = classSet({
            'create-user-form user-form form': true,
            'user-nickname-reuse-form': sameNicknameDismissed,
        });

        let caption = {
            done: i18n('common.action.add'),
            cancel: i18n('common.action.cancel'),
        };

        if (sameNicknameDismissed !== undefined) {
            caption = {
                done: i18n('common.action.save'),
                cancel: i18n('user.action.back_to_form'),
            };
        }

        return (
            <Form
                className={className}
                onSubmit={this._handleFormSubmit}
                autoComplete="off"
            >

                {this._renderNicknameReuseWarning()}

                <Identity errors={errors} />
                <Form.Separator />
                <Login errors={errors} />
                <Password errors={errors} />
                <Contacts errors={errors} />
                <Department errors={errors} department={department} />
                <Form.Error value={errors._common} mod="standalone" />

                <Form.Buttons mod="aligned">
                    <Button text={submitButtonText || caption.done} theme="action" size="m" type="submit" />
                    {removeCancelButton ?
                        null :
                        <Button
                            text={caption.cancel}
                            theme="normal"
                            size="m"
                            onClick={this._cancel}
                        />}
                </Form.Buttons>
            </Form>
        );
    },
});

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

export default Create;
