import PropTypes from 'prop-types';
import React from 'react';
import { Permissions } from 'constants/Common';
import { NOTIFICATION_TIMEOUT } from 'constants/Notifications';
import KeyCodes from 'constants/KeyCodes';
import { i18n } from 'lib/i18n';
import notify from 'services/notify';

import ConfigStore from 'stores/Config';
import AuthStore from 'stores/Auth';
import UserStore from 'stores/Users';
import PermissionStore from 'stores/Permissions';
import OrgProfileActions from 'actions/OrgProfile';
import ModalActions from 'actions/Modal';

import Input from 'lego-ui/Input';
import Icon from 'ui/Icon';

function getEmail(login) {
    if (!login || login.indexOf('@') !== -1) {
        return login;
    }

    return `${login}@yandex.${ConfigStore.get('app.tld')}`;
}

const OrgOwner = React.createClass({

    getInitialState() {
        const { organization } = this.props;
        let login = organization.get('owner_login');

        if (!login) {
            const admin = UserStore.get(organization.get('admin'));

            login = admin ? admin.get('email') : null;
        }

        return { login };
    },

    componentDidUpdate(prevProps) {
        if (prevProps.organization !== this.props.organization) {
            this.setState(this.getInitialState());
        }
    },

    _onStartEdit() {
        this.setState({
            editable: true,
            oldLogin: this.state.login,
        });
    },

    _sendConfirmedChanges() {
        this.setState({
            editable: false,
            busy: true,
        });

        const orgId = AuthStore.getOrganizationId();

        OrgProfileActions.changeOwner({ login: this.state.login })
            .then(data => OrgProfileActions.checkOwnerChangeStatus({
                org_id: orgId,
                task_id: data.task_id,
            }))
            .then(status => {
                if (status === 'success') {
                    this._acceptChanges();
                } else {
                    this._cancelChanges();
                }
            })
            .catch(e => {
                notify(i18n(`backend_errors.org.change_owner.${e.code}`), 'error');
                this._cancelChanges();
            });
    },

    _submitChanges() {
        const messageKey = AuthStore.isExternalAdmin() ? 'external_owner' : 'internal_owner';

        ModalActions.confirm({
            title: i18n('organization_profile.owner.warning.title'),
            message: i18n(`organization_profile.owner.warning.content.${messageKey}`, {
                email: getEmail(this.state.login),
            }),
            mod: 'warning',
            onConfirm: () => this._sendConfirmedChanges(),
            confirmButtonText: i18n('organization_profile.owner.warning.confirm'),
        });
    },

    _acceptChanges() {
        this.setState({
            busy: false,
            editable: false,
            oldLogin: null,
        });

        notify(i18n('organization_profile.owner_updated'), 'success');

        setTimeout(() => location.reload(), NOTIFICATION_TIMEOUT);
    },

    _cancelChanges() {
        this.setState({
            busy: false,
            editable: false,
            login: this.state.oldLogin,
            oldLogin: null,
        });
    },

    _hasValidChanges() {
        const { login, oldLogin } = this.state;

        return login && login !== oldLogin;
    },

    _onKeyDown(event) {
        if (event.keyCode === KeyCodes.ENTER && this._hasValidChanges()) {
            event.stopPropagation();
            event.preventDefault();

            this._submitChanges();
        }
    },

    _onInput(event) {
        this.setState({ login: event.target.value });
    },

    render() {
        const { login, editable } = this.state;
        const components = {};

        if (editable) {
            components.value = (
                <Input
                    defaultValue={login}
                    placeholder={i18n('organization_profile.owner.placeholder')}
                    tip={i18n('organization_profile.owner.tip')}
                    tipPosition="bottom"
                    border="bottom"
                    onInput={this._onInput}
                    onKeyDown={this._onKeyDown}
                    ref={element => element && element.focus()}
                />
            );
            components.actions = [
                <Icon
                    key="submit"
                    type="ok-grey"
                    title={i18n('common.action.save')}
                    disabled={!this._hasValidChanges()}
                    onClick={this._submitChanges}
                />,
                <Icon
                    key="cancel"
                    type="cross"
                    title={i18n('common.action.cancel')}
                    onClick={this._cancelChanges}
                />,
            ];
        } else {
            components.value =
                <span className="org-profile__owner__login" title={login}>{login || '—'}</span>;
            if (PermissionStore.contains(Permissions.CHANGE_OWNER)) {
                components.actions = [
                    <Icon
                        key="edit"
                        type="pen"
                        title={i18n('organization_profile.owner.action.change')}
                        onClick={this._onStartEdit}
                    />,
                ];
            }
        }

        const className = [
            'list separated-subsection',
            'org-profile__owner',
            editable && 'org-profile__owner_editable',
        ].filter(Boolean).join(' ');

        return (
            <div className={className}>
                <div className="list-item">
                    <div className="list-item__key">
                        {i18n('organization_profile.owner.label')}:
                    </div>
                    <div className="list-item__value">
                        <div className="org-profile__owner__value">
                            {components.value}
                            {components.actions}
                        </div>
                    </div>
                </div>
            </div>
        );
    },

});

OrgOwner.propTypes = {
    organization: PropTypes.object.isRequired,
};

export default OrgOwner;
