import PropTypes from 'prop-types';
import React from 'react';
import Popup from 'react-bem-components/lib/Popup';
import ApplicationStore from 'stores/Application';
import UserModalActions from 'actions/Modal.User';
import InviteModalActions from 'actions/Modal.Invite';
import Url from 'lib/Url';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import FlatButton from 'ui/FlatButton';
import Icon from 'ui/Icon';
import AddMenu from './AddMenu';

const Add = React.createClass({

    componentDidMount() {
        const { id } = this.props;
        const displayedDepartment = ApplicationStore.getPrimaryObject();

        if (id === displayedDepartment.id && Url.getInitialAction() === Url.Actions.ADD_USER) {
            // 1. Ждем пока ModalBox выполнит Mount и подпишется на ModalStore
            // 2. Закрываем другие открытые модальные окна
            setTimeout(() => {
                Url.replace(location.pathname);
                UserModalActions.create({ department: id });
            }, 0);
        } else if (id === displayedDepartment.id && Url.getInitialAction() === Url.Actions.INVITE_USER) {
            setTimeout(() => {
                Url.replace(location.pathname);
                InviteModalActions.create({ department: id });
            }, 0);
        }

        this._anchorPopup();
    },

    componentDidUpdate() {
        this._anchorPopup();
    },

    _anchorPopup() {
        if (this.refs.addPopup && this.refs.addControl) {
            this.refs.addPopup.setAnchor(this.refs.addControl);
        }
    },

    _handleAddClick() {
        if (this.refs.addPopup) {
            Metrika.send('Структура', 'Клик на плюсик');
            this.refs.addPopup.block.toggleMod('visible');
        }
    },

    _handleMenuSelect() {
        if (this.refs.addPopup) {
            this.refs.addPopup.close();
        }
    },

    render() {
        const { id, title } = this.props;

        return (
            <div
                className="add-section-item-control"
                ref="addControl"
            >
                <FlatButton
                    className="plus-button"
                    onClick={this._handleAddClick}
                    width="available"
                    ariaLabel={title}
                >

                    <Icon type="plus-solid-circle" />
                    <FlatButton.Label>{i18n('common.action.add')}</FlatButton.Label>
                </FlatButton>
                <Popup
                    ref="addPopup"
                    closable
                    directions={['top-center']}
                    target="anchor"
                >
                    <AddMenu id={id} onSelect={this._handleMenuSelect} />
                </Popup>
            </div>
        );
    },
});

Add.propTypes = {
    id: PropTypes.string,
    title: PropTypes.string,
};

export default Add;
