import * as React from "react";

import "../style/search.scss";
import Sugestion from "./Sugestion";
import { Suggestion, SuggestionType } from "../types/Suggestion";
import getGoogleSuggestions from "../functions/getGoogleSuggestions";

interface State {
	sugestions: Suggestion[];
}

class Search extends React.Component<{}, State> {

	private searchInput = React.createRef<HTMLInputElement>()

	constructor(props) {
		super(props);

		this.state = {
			sugestions: []
		};
	}

	handleQuery(query: string) {
		this.search(query);
	}

	search(query: string) {
		const url = new URL("https://duckduckgo.com/");
		const param = new URLSearchParams();
		param.append("q", query);
		url.search = param.toString();
		window.location.href = url.toString();
	}

	async sugest(input: string) {
		if (input === "") {
			this.setState({
				sugestions: []
			});
		} else {
			const results = await getGoogleSuggestions(input);

			const newSuggestionState: Suggestion[] = results.suggestions.map((e) => {
				return {
					display: e,
					type: SuggestionType.QUERY
				};
			});

			this.setState({
				sugestions: newSuggestionState
			});
		}


	}

	onKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
		if (event.key === 'Enter') {
			this.handleQuery(this.searchInput.current.value);
		} else if (event.key === "ArrowDown") {
			console.log("down");
		} else if (event.key === "ArrowUp") {
			console.log("up");
		}
	}

	onChange() {
		this.sugest(this.searchInput.current.value);
	}

	onSugestionClick(e: Suggestion) {
		if (e.type === SuggestionType.QUERY) {
			this.search(e.display);
		} else {
			window.location.href = e.url;
		}
	}

	render(): JSX.Element {
		return <div className="search-component" >
			<input type="text"
				autoFocus
				onKeyDown={(e) => this.onKeyDown(e)}
				onChange={() => this.onChange()}
				ref={this.searchInput}
				autoComplete="off"
			/>

			<div className="suggestion-area">
				{this.state.sugestions.map((e) => {
					return <Sugestion
						key={e.display}
						suggestion={e}
						onClick={() => { this.onSugestionClick(e); }}
					/>;
				})}
			</div>
		</div>;
	}

}

export default Search;
