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 { getSuggests } from '../../../actions';
import debounce from 'debounce-promise';
import { set as _set, get as _get } from 'lodash';
import AsyncSelect from 'react-select/async';

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

const suggestsAddress = debounce(suggestsAddressDebounce, 200);

export default class AddressSuggestsSelect extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			options: [], 
			fias: [], 
			value: "", 
			value_selected: "", 
			custom: false, 
		};
	}

	componentDidMount()
	{
		//console.log("AddressSuggestsSelect", "this.props", this.props);

		////console.log("AddressSuggestsSelect", this.props);

		this.setState({ value: this.props.value, custom: this.props.value !== "" ? true : false });
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(prevProps.value !== this.props.value)
		{
			////console.log("WTF");

			this.setState({ value: this.props.value });
		}
	}

	_handle_onChange = (data) => 
	{
		////console.log("AddressSuggestsSelect", "_handle_onChange");


		const { fias } = this.state;
		this.setState({ value_selected: data.value, value: data.value, custom: false, }, () => 
		{
			this.props.onChange({ title: data.value, fias_id: fias[data.value] });
		});
	}

	_handle_onBlur = (data, action) => 
	{
		////console.log("AddressSuggestsSelect", "_handle_onBlur");

		const { value, value_selected } = this.state;
		////console.log("_handle_onBlur", { value, value_selected }, { action });


		//if(value_selected !== "")
		//{
		//	this.setState({ value_selected: "" });
		//}
		//else
		//{
			////console.log("this", value);

			//this.props.onChange({ title: value, fias_id: "" });
		//}
	}

	_handle_onInputChange = (value, action) => 
	{
		////console.log("AddressSuggestsSelect", "_handle_onInputChange", action, { value });


		if(action.action === "input-blur")
		{
			setTimeout(() => 
			{
				//console.log("this.state.value_selected", this.state.value_selected);

				if(this.state.value_selected === "")
				{
					this.setState({ custom: true }, () => 
					{
						this.props.onChange({ title: action.prevInputValue, fias_id: "" });
					});
				}
			}, 10);
		}
		else
		{
			if(action.action === "input-change")
			{
				this.setState({ value });
			}
		}
		/*
		if (action.action !== "input-blur" && action.action !== "menu-close") 
		{
			this.setState({ value });
			//console.log("AddressSuggestsSelect", "_handle_onInputChange", 1);

		}
		else
		{
			if(action.action === "input-blur" && action.prevInputValue !== "" && value === "")
			{
				this.setState({ value: action.prevInputValue, custom: true, }, () => 
				{
					//console.log("AddressSuggestsSelect", "_handle_onInputChange", 2, "[", action.prevInputValue, "]");

					this.props.onChange({ title: action.prevInputValue, fias_id: "" });
				});
			}
			else
			{
				if(value === "" && action.prevInputValue === "")
				{
					this.setState({ value, value_selected: "", custom: false, }, () => 
					{
						//console.log("AddressSuggestsSelect", "_handle_onInputChange", 3, "[", value, "]", "{", action.prevInputValue, "}");

						this.props.onChange({ title: action.prevInputValue, fias_id: "" });
					});
				}
			}
		}
		*/
		//this.setState({ value });
	}

	_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 { value, value_selected, custom } = this.state;
		const { disabled } = this.props;

		if(custom)
		{
			return (
				<AsyncSelect 
					inputValue={ value } 
					placeholder="Укажите адрес" 
					className="autocomplete" 
					classNamePrefix="react-select" 
					cacheOptions={ true } 
					defaultOptions={ this.state.options } 
					noOptionsMessage={ () => null } 
					loadingMessage={ () => null } 
					loadOptions={ (text) => this._getAddress(text) } 
					onChange={ this._handle_onChange } 
					//onBlur={ this._handle_onBlur } 
					onInputChange={ this._handle_onInputChange } 
					//isDisabled={ disabled ? true : false } 
				/>
			)
		}
		else
		{
			return (
				<AsyncSelect 
					//value={ value } 
					defaultInputValue={ value } 
					placeholder="Укажите адрес" 
					className="autocomplete" 
					classNamePrefix="react-select" 
					cacheOptions={ true } 
					defaultOptions={ this.state.options } 
					noOptionsMessage={ () => null } 
					loadingMessage={ () => null } 
					loadOptions={ (text) => this._getAddress(text) } 
					onChange={ this._handle_onChange } 
					//onBlur={ this._handle_onBlur } 
					onInputChange={ this._handle_onInputChange } 
					//isDisabled={ disabled ? true : false } 
				/>
			)
		}
	}
}