import React from 'react';
import { Icon, TextInput } from 'lego-on-react';
import buildString from '@connect/string-placeholders';
import { block } from 'bem-cn';
import SearchList from 'components2/SearchList';
import { Search as SearchIcon } from 'components/Icon';
import { i18n } from 'i18n2';
import { ConfigStore } from 'lib2/stores';
import getOrganization from 'lib2/getOrganization';
import toDirectoryObject from 'lib2/toDirectoryObject';

import './index.css';

const b = block('search-input');
const Key = { ENTER: 13, UP: 38, DOWN: 40 };

const SearchOptions = {
    all: {
        'people.per_page': 10,
        'departments.per_page': 10,
        'groups.per_page': 10,
    },
    user: {
        layers: 'people',
        'people.per_page': 10,
    },
};

function openSearch(text) {
    window.location.href = buildString(ConfigStore.get('ui.search'), {
        host: window.location.host,
        query: encodeURIComponent((text || '').replace(/\s+/g, '+')),
        org_id: getOrganization().id,
    });
}

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

        this.state = {
            text: props.text || '',
        };

        this._onChange = this._onChange.bind(this);
        this._onKeyDown = this._onKeyDown.bind(this);
        this._onSelect = this._onSelect.bind(this);
        this._onContainerKeyDown = this._onContainerKeyDown.bind(this);
        this._onIconClick = this._onIconClick.bind(this);

        this._initContainer = this._initContainer.bind(this);
        this._initInput = this._initInput.bind(this);
    }

    _onChange(text) {
        this.setState({ text });
    }

    _onKeyDown(event) {
        if (event.keyCode === Key.DOWN) {
            try {
                this._container.querySelector('.menu').focus();
                event.preventDefault();
            } catch (e) { /* ignore */ }
        }

        if (event.keyCode === Key.ENTER && this.props.type === 'navigation') {
            openSearch(this.state.text);
        }
    }

    _onSelect(event, item) {
        let { type, onSelect } = this.props;

        if (type === 'navigation') {
            window.location.href = item.url;
        }

        if (onSelect) {
            onSelect(toDirectoryObject(item));

            this.setState({ text: '' }, () => this._input.focus());
        } else {
            this.setState({ text: item.title });
        }
    }

    _onContainerKeyDown(event) {
        if (![Key.UP, Key.DOWN, Key.ENTER].includes(event.keyCode)) {
            this._input.focus();
        }
    }

    _onIconClick() {
        openSearch(this.state.text);
    }

    _initContainer(element) {
        this._container = element;
    }

    _initInput(element) {
        this._input = element;
    }

    focus() {
        this._input.focus();
    }

    render() {
        let { text } = this.state;
        let {
            cls,
            id,
            searchType = 'all',
            placeholder,
            showSearchIcon,
            checked,
            onFocus,
            onBlur,
        } = this.props;

        if (placeholder === undefined) {
            placeholder = i18n(`common.suggest_search_placeholder.${searchType}`);
        }

        return (
            <div
                className={b('container').mix(cls)}
                onKeyDown={this._onContainerKeyDown}
                ref={this._initContainer}
            >
                <TextInput
                    theme="normal"
                    size="m"
                    cls={b()}
                    id={id}
                    text={text}
                    onChange={this._onChange}
                    onKeyDown={this._onKeyDown}
                    iconRight={showSearchIcon && (
                        <Icon glyph="yes">
                            <span
                                className={b('icon')}
                                onClick={this._onIconClick}
                            >
                                <SearchIcon />
                            </span>
                        </Icon>
                    )}
                    onFocus={onFocus}
                    onBlur={onBlur}
                    placeholder={placeholder}
                    hasClear
                    autoComplete={false}
                    ref={this._initInput}
                />
                <SearchList
                    theme="normal"
                    size="m"
                    cls={b('search-list')}
                    text={text}
                    onClick={this._onSelect}
                    options={SearchOptions[searchType]}
                    checked={checked}
                />
            </div>
        );
    }
}
