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

import Popup from 'react-bem-components/lib/Popup';
import FlatButton from 'ui/FlatButton';
import Icon from 'ui/Icon';
import EditMenu from './EditMenu';

const Edit = React.createClass({

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

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

    _anchorPopup() {
        if (this.refs.editPopup && this.refs.editControl) {
            this.refs.editPopup.setAnchor(this.refs.editControl);
        }
    },

    _handleEditClick() {
        if (this.refs.editPopup) {
            this.refs.editPopup.block.toggleMod('visible');
        }
    },

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

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

        return (
            <div
                className="edit-group-controls edit-section-controls"
                ref="editControl"
            >
                <FlatButton
                    onClick={this._handleEditClick}
                    ariaLabel={title}
                >

                    <Icon type="dots" />
                </FlatButton>
                <Popup
                    ref="editPopup"
                    closable
                    directions={['bottom-right']}
                    target="anchor"
                >
                    <EditMenu id={id} onSelect={this._handleMenuSelect} />
                </Popup>
            </div>
        );
    },
});

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

export default Edit;
