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 { getAddress, getSuggests } from '../../actions';

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

const suggestsAddress = debounce(suggestsAddressDebounce, 200);

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

	componentDidMount()
	{
	}

	componentDidUpdate(prevProps, prevState)
	{
	}

	_handle_onChange = (value) => 
	{
		const { fias, focused } = this.state;
		const { onChange } = this.props;

		onChange({ name: value, fias_id: "" });
		this.setState({ focused: true }, () => 
		{
			this._getAddress(value);
		});

		//if(focused)
		//{
		//}	
	}

	_handle_onSelect = (value) => 
	{
		const { fias, focused } = this.state;
		const { onChange } = this.props;

		onChange({ name: value, fias_id: fias[value] });
		setTimeout(() => 
		{
			this.setState({ focused: false });
		}, 100);
	}

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

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

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

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

		return (
			<div className="autocomplete" style={{ position: "relative" }}>
				<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 && className }` }
					id="address" 
					name="address" 
					value={ value } 
					placeholder={ placeholder !== undefined ? placeholder : "Введите адрес" } 
					onChange={ (event) => this._handle_onChange(event.target.value) } 
					onFocus={ this._handle_onFocus } 
					onBlur={ this._handle_onBlur } 
					onMouseDown={ (event) => { this._handle_onFocus(event); } } 
					onTouchStart={ (event) => { this._handle_onFocus(event); } }
					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 }_${ option.value }` } 
									onMouseDown={ (event) => { event.preventDefault(); this._handle_onSelect(option.value); } } 
									onTouchStart={ (event) => { event.preventDefault(); this._handle_onSelect(option.value); } } 
								><span>{ option.value }</span></div>
							)) }
						</div>
					</div>
				) }
			</div>
		);
	}
}