import React, {component} from 'react';
import { Button,  Icon,Autocomplete,  Input} from 'react-materialize';

import './MyAutocomplete.css';
class MyAutocomplete extends React.Component {

	constructor(props){
		super(props);
		this.state = {
			autoComplete: false,
			value: props.value || '',
			selected: -1
		}
	}

	componentWillReceiveProps(props) {
		this.search(this.state.value, props);
	}

	select(item) {
		let { onComplete } = this.props;

		onComplete && onComplete(this.state.value, item);
	}

	search(term, props) {
		if (term.length < 2) {
			this.setState({
				autoComplete: false
			});
			return;
		}
		let {
			data,
			options
		} = props;


		let values = Object.keys(data);
		values.sort((a,b) => a.localeCompare(b));
		values = values.map((item) => item.toUpperCase());
		let segments = term.toUpperCase().split(' ');
		let dataset = Object.keys(data).reduce((res,a) => {
			res[a.toUpperCase()] = data[a];
			return res;
		}, {});
		let correct = values.filter((item) => segments.reduce((res, seg) => res && item.includes(seg), true));
		correct = correct.slice(0,this.props.options.limit);
		this.setState({
			autoComplete: correct.length > 0,
			autoCompleteData: correct,
			data: dataset
		});
	}

	change(e) {
		let term = e.target.value;

		let {
			onChange
		} = this.props;

		this.search(term, this.props);

		onChange && onChange(e);
		this.setState({ value: term });
	}

	keyHandler(e) {
		console.log(e.keyCode)
		if(e.keyCode === 40) {
			this.setState({
				selected: this.state.selected < (this.state.autoCompleteData.length - 1) ? this.state.selected + 1 : this.state.autoCompleteData.length - 1
			})
		} else if(e.keyCode === 38) {
			this.setState({
				selected: this.state.selected > 0 ? this.state.selected - 1 : 0
			})
		} else if(e.key === "Enter") {
			e.preventDefault();
			if (this.state.selected > -1) {
				this.select(this.state.data[this.state.autoCompleteData[this.state.selected]]);
			} else {
				this.select({ key: this.state.value });
			}
		}
	}

	render(){
		return(
	    <div className={'MyAutocomplete ' + this.props.className}>
	        <form autoComplete="off" style={{ flexGrow: 1 }}>
	      		<input onChange={(e) => this.change(e)} value={this.state.value} placeholder={this.props.placeholder || 'Search'} className="autocomplete-options-fa98bb6c-92e7-abe2-025b-b9f8e505ff98" onKeyDown={(e) => this.keyHandler(e)}/>
	        </form>
  			{this.state.autoComplete ?
  				<ul id="autocomplete-options-d483f2ec-fa7d-1905-b56c-81047362fa8e" className={"autocomplete-content dropdown-content " + (this.state.autoComplete ? "myautocomplete-visible" : "")} tabindex="0">
	  				{this.state.autoCompleteData.map((item, indx) => {
		  				return <li key={item} onClick={() => this.select(this.state.data[item])} className={this.state.selected === indx ? "active": ""} onMouseEnter={() => this.setState({selected: -1})}>
		  					{this.state.data[item] && <img src={this.state.data[item].image} class="right circle"/>}
		  					<span>{item}</span>
		  				</li>
	  				}
	  				)}
				</ul> : null}
        </div>);  
		}
}

export default MyAutocomplete;
