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

import { updateQuestionnaire, getAddress, getSuggests, resetQuestionnaire, questionnaireSetSign } from "../../../actions";

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

const suggestsAddress = debounce(suggestsAddressDebounce, 200);

export default class QuestionnaireForm extends React.Component 
{
	_updateQuestionnaire = (questionnaire) => 
	{
		return new Promise((resolve, reject) => 
		{
			updateQuestionnaire({ dispatch: this.props.dispatch, questionnaire })
			.then(() => 
			{
				resolve();
			})
			.catch(() => 
			{

			});
		});
	}

	_checkStrValue = (value) => 
	{
		return value !== undefined && value !== null ? value.toString() : "";
	}

	_checkDateValue = (value) => 
	{
		return typeof value === 'string' ? value : "";
	}

	_checkStrNotEmpty = (value) => 
	{
		if(value === null || value === undefined || value === "")
		{
			return false;
		}
		return true;
	}

	_getAddress = (name, text) => 
	{
		return new Promise((resolve, reject) => 
		{
			suggestsAddress(text)
			.then((result) => 
			{
				const update = {};
				update[name] = result.suggestions;
				this.setState(update, () => 
				{
					resolve(result.suggestions.map(s => ({ value: s.value, label: s.value })));
				});
			})
			.catch(() => 
			{

			});
		})
	}

	_removeError = (name) => 
	{
		//console.log("_removeError", name, typeof name);

		const errors = [ ...this.state.errors ];

		if(typeof name === "string")
		{
			if(errors.indexOf(name) > -1)
			{
				errors.splice(errors.indexOf(name), 1);
			}
		}
		else
		{
			for(let i in name)
			{
				//console.log("REMOVE", name[i]);

				if(errors.indexOf(name[i]) > -1)
				{
					errors.splice(errors.indexOf(name[i]), 1);
				}	
			}
		}

		this.setState({ errors });
	}

	_handle_onTextFieldChange = (name, value) => 
	{
//		console.log("QuestionnaireForm", "_handle_onTextFieldChange", { name, value });

		const update = { ...this.state };
		_set(update, name, value);
		this._updateQuestionnaire(update);
	}

	_handle_onDateFieldChange = (name, value, raw) => 
	{
//		console.log("QuestionnaireForm", "_handle_onDateFieldChange", { name, value, raw });

		if(value === null && raw === null)
		{
			const update = { ...this.state };
			_set(update, name, null);
			this._updateQuestionnaire(update);	
		}
		else
		{
			try
			{
				const date = moment.utc(raw, 'DD.MM.YYYY').format('YYYY-MM-DD');

				const update = { ...this.state };
				_set(update, name, date);
				this._updateQuestionnaire(update);	
			}
			catch(e)
			{
				console.error(e);
			}
		}
	}

	_handle_onCheckboxFieldChange = (name, value) => 
	{
		//console.log("QuestionnaireForm", "_handle_onCheckboxFieldChange", { name, value });

		const update = { ...this.state };
		_set(update, name, value);
		this._updateQuestionnaire(update);
	}

	_handle_onFieldChange = (name, payload) => 
	{
		//console.log("_handle_onFieldChange", name, payload);


		const update = { ...this.state };
		_set(update, name, payload);

		this._updateQuestionnaire(update);
	}

	_handle_onBranchChange = (payload) => 
	{
		//console.log("_handle_onBranchChange", payload);


		const update = JSON.parse(JSON.stringify(global.store.getState().questionnaire));
		for(let i in payload)
		{
			_set(update, payload[i].name, payload[i].value);
		}

		this._updateQuestionnaire(update);
	}

	_handle_onJoinChange = (payload) => 
	{
		//console.log("_handle_onJoinChange", payload);

		this._updateQuestionnaire(payload);
	}

	_handle_onAddFile = (name, files) => 
	{
		//console.log("QuestionnaireForm", "_handle_onAddFile", { name, files });


		const existed_files = [ ..._get(this.state, name) ];
		for(let nf in files)
		{
			let e = false;
			for(let ef in existed_files)
			{
				if(existed_files[ef].name === files[nf].name) { e = true; }
			}

			if(!e)
			{
				existed_files.push(files[nf]);
			}
		}

		const update = { ...this.state };
		_set(update, name, existed_files);

		//console.log("_handle_onAddFile", "update", update);

		this._updateQuestionnaire(update);
	}

	_handle_onRemoveFile = (group, id) => 
	{
		const existed_files = [ ..._get(this.state, group) ];
		//console.log("QuestionnaireForm", "_handle_onRemoveFile", { group, id, existed_files });


		const files = [];
		for(let i in existed_files)
		{
			if(existed_files[i].id !== id)
			{
				files.push(existed_files[i]);
			}
		}

		const update = { ...this.state };
		_set(update, group, files);
		//console.log("_handle_onRemoveFile", "group", "files", group, files);


		this._updateQuestionnaire(update);
	}

	_handle_onReset = (event) => 
	{
		event.preventDefault();
		const { dispatch } = this.props;
		
		const reset = window.confirm("Вы действительно хотите отменить изменения, внесенные в анкету? Состояние анкеты будет сброшено до версии, имеющейся у ООО \"ЛК Эволюция\"");
		if(reset)
		{
			this.props.onNextStep("main");
			resetQuestionnaire({ dispatch, id: this.props.company.questionnaire_id });
		}
	}

	_handle_onSignDigital = () => 
	{
		const { dispatch } = this.props;
		questionnaireSetSign({ dispatch, sign: { digital: true, print: false, }});
		setTimeout(() => 
		{
			this.props.onSuccess();
			this.props.onNextStep("status");
		}, 10);	
	}
}