import omit from 'lodash/omit';
import React from 'react';
import { Menu } from 'lego-on-react';
import { block } from 'bem-cn';
import { search } from 'api2/suggest';
import AvatarUnit from 'components2/AvatarUnit';
import toDirectoryObject from 'lib2/toDirectoryObject';
import { i18n } from 'i18n2';

import './index.css';

const b = block('search-list');

const DisplayOrder = ['people', 'departments', 'groups'];

function compareSearchItems(x, y) {
    if (x.title === y.title) {
        return 0;
    }

    return x.title > y.title ? -1 : 1;
}

function isEmpty(data) {
    return !data || Object.values(data).every(item => !item.result || !item.result.length);
}

export default class extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {};
    }

    componentDidUpdate(prevProps) {
        let { text, options = {} } = this.props;

        if (text !== prevProps.text) {
            clearTimeout(this._timeout);

            this._timeout = setTimeout(() => {
                search({ text, ...options }).then(({ body }) => {
                    if (this.props.text === text) {
                        this.setState({ data: body });
                    }
                });
            }, 50);
        }
    }

    render() {
        let { data } = this.state;

        if (isEmpty(data)) {
            return null;
        }

        let menuProps = omit(this.props, ['text', 'cls', 'options', 'checked']);

        let { cls, options = {}, checked } = this.props;
        // не показываем заголовок группы в выдаче,
        // если в options.layers явно задан только один тип объектов
        let withGroupTitles = !options.layers || options.layers.includes(',');

        return (
            <Menu
                {...menuProps}
                cls={b({}).mix(cls)}
                type="radiocheck"
            >
                {DisplayOrder.map(layer => {
                    let list = data[layer] && data[layer].result;

                    return list && list.length !== 0 && (
                        <Menu.Group
                            title={withGroupTitles ? i18n(`search.suggest.${layer}`) : null}
                            cls={b('group', { layer })}
                            key={layer}
                        >
                            {list.sort(compareSearchItems).map(item => {
                                let directoryItem = toDirectoryObject(item);

                                return (
                                    <Menu.Item
                                        val={item}
                                        cls={b('item', {
                                            checked: checked && checked(directoryItem),
                                        })}
                                        key={item.id}
                                    >
                                        <AvatarUnit
                                            object={directoryItem.object}
                                            type={directoryItem.type}
                                        />
                                    </Menu.Item>
                                );
                            })}
                        </Menu.Group>
                    );
                })}
            </Menu>
        );
    }
}
