import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { block } from 'bem-cn';
import { Button, Icon, Image } from 'lego-on-react';
import StoreMixin from 'lib/StoreMixin';
import notify from 'services/notify';
import { i18n } from 'lib/i18n';

import ModalActions from 'actions/Modal';
import ServicesActions from 'actions/Services';
import UserStore from 'stores/Users';
import ResourcesStore from 'stores/Resources';
import PermissionStore from 'stores/Permissions';

import SuggestPicker from 'components/SuggestPicker';
import Popup from 'components/Popup';

import editIcon from '../../../static/i/edit.svg';

import './Responsible.css';

const bServiceResponsible = block('service-responsible');

export default React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        const { serviceSlug } = this.props;
        const nextState = {
            storedUserId: ResourcesStore.getResponsibleId(serviceSlug),
            popupActive: false,
            editable: PermissionStore.allowsServiceDataUpdate(serviceSlug),
        };

        // если поле ввода ещё не было отредактировано
        if (!this.state || this.state.userId === undefined) {
            nextState.userId = nextState.storedUserId;
        }

        return nextState;
    },

    componentDidMount() {
        this.subscribe([ResourcesStore, UserStore]);
    },

    _handlePickerChange(items) {
        const user = items[0];

        if (user) {
            const nextUserId = user.getId();

            this.setState({
                userId: nextUserId,
                hasChanges: this.state.storedUserId !== nextUserId,
            });
        } else {
            this.setState({
                userId: null,
                hasChanges: false,
            });
        }
    },

    _onSubmit() {
        return ModalActions.confirm({
            message: i18n('services.responsible.confirm.message'),
            confirmButtonText: i18n('services.responsible.confirm.ok'),
            onConfirm: () => this._onConfirmedSubmit(),
        });
    },

    _onConfirmedSubmit() {
        const { props, state } = this;

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

        ServicesActions.update(props.serviceSlug, { responsible_id: Number(state.userId) })
            .then(response => {
                if (response.errors) {
                    return notify(i18n('services.responsible.failed_to_update'), 'error');
                }

                this.setState({
                    storedUserId: String(state.userId),
                    hasChanges: false,
                    popupActive: false,
                });

                notify(i18n('services.responsible.successfully_updated'), 'success');
            })
            .catch(() => {
                notify(i18n('services.responsible.failed_to_update'), 'error');
            })
            .finally(() => {
                this.setState({
                    busy: false,
                });
            });
    },

    _reset() {
        this.setState({
            hasChanges: false,
            userId: this.state.storedUserId,
            popupActive: false,
        });
    },

    _openPopup() {
        this.setState({ popupActive: true });
    },

    _renderEdit() {
        const { userId, hasChanges, busy, editable } = this.state;

        if (!editable) {
            return [];
        }

        const user = userId ? UserStore.get(userId) : null;

        return [
            <Button
                theme="clear"
                size="s"
                icon={<Icon url={editIcon} />}
                onClick={this._openPopup}
                key="edit-button"
            />,
            <Popup active={this.state.popupActive} key="edit-popup">
                <SuggestPicker
                    suggest
                    multiple={false}
                    placeholder={i18n('services.responsible.placeholder')}
                    onChange={this._handlePickerChange}
                    type="user"
                    value={user ? [user] : null}
                />
                <div className={bServiceResponsible('actions')}>
                    <Button
                        theme="action"
                        view="default"
                        tone="default"
                        size="s"
                        disabled={!hasChanges || busy}
                        progress={busy}
                        onClick={this._onSubmit}
                        text={i18n('common.action.save')}
                    />
                    <Button
                        theme="normal"
                        onClick={this._reset}
                        size="s"
                        text={i18n('common.action.cancel')}
                    />
                </div>
            </Popup>,
        ];
    },

    render() {
        const storedUser = UserStore.get(this.state.storedUserId);

        if (!storedUser) {
            return null;
        }

        let position;

        if (storedUser.getPosition()) {
            position = <p className={bServiceResponsible('position')}>{storedUser.getPosition()}</p>;
        }

        return (
            <div className={bServiceResponsible()}>
                <Image url={storedUser.getAvatar()} cls={bServiceResponsible('avatar')} />
                <div className={bServiceResponsible('info')}>
                    <p className={bServiceResponsible('name')}>{storedUser.getName()}</p>
                    {position}
                </div>
                {this._renderEdit()}
            </div>
        );
    },

});
