import React from "react";
import Head from 'next/head';
import Image from 'next/image';
import Link from "next/link";
import cookie from 'cookie';
import { connect } from "react-redux";
import numeral from "numeral";
import pluralize from 'pluralize-ru';
import { SpinnerCircular } from 'spinners-react';
import AsyncSelect from 'react-select/async';
import debounce from 'debounce-promise';
import { set as _set, get as _get } from 'lodash';

import { getSuggests } from '../../actions';

const suggestsAddressDebounce = (query) =>
{
	return getSuggests("address", { query });
}

const suggestsFirstnameDebounce = (query) =>
{
	return getSuggests("name", { query, parts: ["NAME"] });
}

const suggestsMiddlenameDebounce = (query) =>
{
	return getSuggests("name", { query, parts: ["PATRONYMIC"] });
}

const suggestsLastnameDebounce = (query) =>
{
	return getSuggests("name", { query, parts: ["SURNAME"] });
}

const suggestsIssuerDebounce = (query, max) =>
{
	return getSuggests("document/issuer", { query, max });
}

const suggestsAddress = debounce(suggestsAddressDebounce, 200);
const suggestsFirstname = debounce(suggestsFirstnameDebounce, 200);
const suggestsMiddlename = debounce(suggestsMiddlenameDebounce, 200);
const suggestsLastname = debounce(suggestsLastnameDebounce, 200);
const suggestsIssuer = debounce(suggestsIssuerDebounce, 200);

export default class DocumentIssuerSuggestsInput extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			focused: false, 
			options: [], 
		};
	}

	componentDidMount()
	{
	}

	componentDidUpdate(prevProps, prevState)
	{
	}

	_handle_onChange = (value) => 
	{
		//console.log("DocumentIssuerSuggestsInput", "_handle_onChange", { value });

		const { focused } = this.state;
		const { onChange } = this.props;

		onChange(value);
		if(focused)
		{
			this._getValue(value);
		}
	}

	_handle_onSelect = (option) => 
	{
		//console.log("DocumentIssuerSuggestsInput", "_handle_onSelect", { option });

		const { onChange } = this.props;

		onChange(option);
		setTimeout(() => 
		{
			this.setState({ focused: false });
		}, 100);
	}

	_handle_onFocus = () => 
	{
		this.setState({ focused: true });
	}

	_handle_onBlur = () => 
	{
		setTimeout(() => 
		{
			this.setState({ focused: false });
		}, 100);
	}

	_getSuggests = (text) => 
	{
		const { type, maxResults } = this.props;

		return new Promise((resolve, reject) => 
		{
			if(type === "lastname")
			{
				suggestsLastname(text).then((result) => { resolve(result); }).catch(() => {});
			}

			if(type === "firstname")
			{
				suggestsFirstname(text).then((result) => { resolve(result); }).catch(() => {});
			}

			if(type === "middlename")
			{
				suggestsMiddlename(text).then((result) => { resolve(result); }).catch(() => {});
			}

			if(type === "issuer")
			{
				suggestsIssuer(text, maxResults).then((result) => { resolve(result); }).catch(() => {});
			}
		});
	}

	_getValue = (text) => 
	{
		return new Promise((resolve, reject) => 
		{
			if(text === "")
			{
				this.setState({ options: [], value: "" }, () => 
				{
					resolve([]);
				});
			}
			else
			{
				this._getSuggests(text)
				.then((result) => 
				{
					const options = [];
	
					for(let i in result.suggestions)
					{
						const s = result.suggestions[i];
						options.push({ ...s, value: s.value, label: s.value });
					}

					this.setState({ options  }, () => 
					{
						resolve(options);
					});
				})
				.catch(() => 
				{
	
				});
			}
		})
	}

	render()
	{
		const { focused, options } = this.state;
		const { value, disabled, required, placeholder, name, className, innerStyle } = this.props;

		return (
			<div className="autocomplete" style={{ ...{ position: "relative" }, ...innerStyle, }}>
				<input type="text" 
					autoComplete="off" 
					style={{ width: "100%" }} 
					className={ `react-select__control react-select__control--is-focused ${ focused ? "react-select__control--menu-is-open" : "" } ${ className }` } 
					id={ name } 
					name={ name } 
					value={ value } 
					placeholder={ placeholder !== undefined ? placeholder : "Заполните поле" } 
					onChange={ (event) => this._handle_onChange(event.target.value) } 
					onFocus={ this._handle_onFocus } 
					onBlur={ this._handle_onBlur } 
					required={ required } 
					disabled={ disabled } 
				/>
				{ focused && options.length > 0 && (
					<div className="react-select__menu" style={{ position: "absolute", zIndex: 1000, background: "#fff", width: "100%", left: "0px", top: "40px" }}>
						<div className="react-select__menu-list">
							{ options.map((option, index) => 
							(
								<div 
									className="react-select__option" 
									style={{ minHeight: "26px", background: "#FFF", lineHeight: "18px", margin: "0px", padding: "5px 5px 5px 5px", }} 
									key={ index } 
									onMouseDown={ (event) => { event.preventDefault(); this._handle_onSelect(option); } } 
									onTouchStart={ (event) => { event.preventDefault(); this._handle_onSelect(option); } } 
								><span>{ option.value }</span></div>
							)) }
						</div>
					</div>
				) }
			</div>
		);
	}
}