import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Menu from 'react-bem-components/lib/Menu';
import submit from 'services/submit';
import { i18n } from 'lib/i18n';
import Metrika from 'lib/metrika';

import DepartmentStore from 'stores/Departments';
import AuthStore from 'stores/Auth';
import ModalActions from 'actions/Modal';
import DepartmentActions from 'actions/Department';
import UIActions from 'actions/UI';

const EditMenu = React.createClass({

    _handleMenuSelect(payload) {
        const { id, onSelect } = this.props;

        switch (payload.value) {
            case 'update':
                Metrika.send('Структура', 'КМ в шапке отдела', 'Клик в Редактировать');
                UIActions.editDepartment({ id, mode: 'update' });
                break;

            case 'move':
                Metrika.send('Структура', 'КМ в шапке отдела', 'Клик в Переместить');
                UIActions.editDepartment({ id, mode: 'move' });
                break;

            case 'remove':
                Metrika.send('Структура', 'КМ в шапке отдела', 'Клик в Удалить');

                ModalActions.confirm({
                    message: i18n('department.message.confirm_removal', {
                        department: _.escape(DepartmentStore.getName(id)),
                    }),
                    confirmButtonText: i18n('department.action.remove'),
                    onConfirm() {
                        Metrika.send('Структура', 'Шапка отдела', 'Удаление', 'Удалить');

                        submit(DepartmentActions.removeDepartment(id), {
                            success: i18n('department.status.removed'),
                            failure: i18n('department.status.failed_to_remove'),
                        });
                    },
                });
                break;

        /* no default */
        }

        if (onSelect) {
            onSelect(payload);
        }
    },

    render() {
        const isRoot = DepartmentStore.get(this.props.id).isRoot();
        const hasOwnedDomains = AuthStore.hasOwnedDomains();

        const options = [
            {
                text: i18n('department.edit_menu.update'),
                disabled: isRoot && !hasOwnedDomains,
                val: 'update',
            },
            {
                text: i18n('department.edit_menu.move'),
                disabled: isRoot,
                val: 'move',
            },
            {
                text: i18n('department.edit_menu.remove'),
                disabled: isRoot,
                val: 'remove',
            },
        ];

        return <Menu options={options} onSelect={this._handleMenuSelect} />;
    },
});

EditMenu.propTypes = {
    id: PropTypes.string,
    onSelect: PropTypes.func,
};

export default EditMenu;
