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 Select from 'react-select'
import { SpinnerCircular } from 'spinners-react';
import { connect } from "react-redux";
import { withRouter } from 'next/router';

import QuestionnaireForm from "../QuestionnaireForm";
import { reduxWrapper } from '../../../../store';
import AddressSuggests from "../../AddressSuggests";
import { saveQuestionnaire } from "../../../../actions";
import FormMessage from "../FormMessage";
import { traceDebug } from "../../../../utils";

class Form_2_Contacts extends QuestionnaireForm 
{
	constructor(props)
	{
		super(props);
		this.state = {
			contacts: {
				loading: false, 
	
				fact_address: { 
					name: null, 
					fias_id: null, 
				}, 
				legal_address: { 
					name: null, 
					fias_id: null, 
				}, 
				postal_address: { 
					name: null, 
					fias_id: null, 
				}, 
			}, 
			errors: [], 
		};

		this.ref_form = React.createRef();
		this.ref_submit = React.createRef();
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			main: nextProps.questionnaire.main, 
			contacts: nextProps.questionnaire.contacts, 
			step: nextProps.questionnaire.step, 
			status: nextProps.questionnaire.status, 
		};
	}

	componentDidMount()
	{
		const { company } = this.props;
		const { mail_delivery_address_type } = this.state.main;

		if(company.inn.length > 10 && parseInt(mail_delivery_address_type, 10) === 100000000)
		{
			this._handle_onCheckboxFieldChange("main.mail_delivery_address_type", 100000001);
		}
	}

	_handle_onFormSubmit = (event) => 
	{
		event.preventDefault();

		this._handle_onJoinChange({ status: "draft", step: 3 });
		setTimeout(() => 
		{
			saveQuestionnaire();
			this.props.onNextStep("signer");
		}, 10);
	}

	_handle_onNextPage = () => 
	{
		const { main, contacts } = this.state;

		const errors = [];
		const check = ["fact_address", "legal_address", "postal_address"];

		if(contacts.fact_address.name === "")
		{
			errors.push(`contacts.fact_address`);
		}

		if(parseInt(main.mail_delivery_address_type, 10) === 100000002)
		{
			if(contacts.postal_address.name === "")
			{
				errors.push(`contacts.postal_address`);
			}
		}

		this.setState({ errors }, () => 
		{
			window.scroll(0, 0);
			if(errors.length === 0)
			{
				this.ref_submit.current.click();
			}
			else
			{
				traceDebug({ errors });
			}
		});
	}

	render()
	{
		const { company, checking } = this.props;
		const { main, contacts, loading, status, step, errors } = this.state;
		const { fact_address, postal_address, } = contacts;
		const { mail_delivery_address_type } = main;

		return (
			<React.Fragment>
				<form ref={ this.ref_form } onSubmit={ this._handle_onFormSubmit } onKeyDown={(e) => {if (e.key === 'Enter') e.preventDefault() }} className={`questionnaire questionnaire_2 ${ checking && "disabled" }`}>
					<p className="title">2. Адреса лизингополучателя</p>
					{ errors.length > 0 && 
					( 
						<FormMessage type="error" title="Ошибка" message="Пожалуйста, проверьте корректность заполнения данных в форме."/>
					) }

					<div className="form_field">
						<label>Фактический адрес <sup className="required_label">*</sup></label>
						<AddressSuggests 
							className={ errors.indexOf("contacts.fact_address") > -1 ? "error" : "" } 
							value={ this._checkStrValue(fact_address.name) } 
							fias={ this._checkStrValue(fact_address.fias_id) } 
							onChange={ (data) => { this._removeError("contacts.fact_address"); this._handle_onTextFieldChange("contacts.fact_address", data); } } 
							required={ true } 
							disabled={ false } 
						/>
						<p>для юр.диц - заполняется, если отличается от указанного в ЕГРЮЛ; для ИП - заполняется всегда</p>
					</div>

					<p><b>Прошу оригиналы  счетов-фактур и актов оказанных услуг по заключенному договору лизинга направлять:</b></p>

					<div className="form_field">
						<div style={{ width: "100%" }}>

							{ company.inn.length < 11 && (
								<div className="form_field checkbox">
									<input type="radio" hidden="" 
										value={ 100000000 } 
										id="main.mail_delivery_address_type.legal" 
										name="main.mail_delivery_address_type" 
										checked={ parseInt(mail_delivery_address_type, 10) === 100000000 ? true : false } 
										onChange={ (event) => { this._removeError("contacts.postal_address"); this._handle_onCheckboxFieldChange(event.target.name, parseInt(event.target.value, 10)); } } 
										disabled={ checking } 
									/>
									<label htmlFor="main.mail_delivery_address_type.legal" className="unselectable">По юридическому адресу, указанному в ЕГРЮЛ</label>
								</div>
							) }

							<div className="form_field checkbox">
								<input type="radio" hidden="" 
									value={ 100000001 } 
									id="main.mail_delivery_address_type.fact" 
									name="main.mail_delivery_address_type" 
									checked={ parseInt(mail_delivery_address_type, 10) === 100000001 ? true : false } 
									onChange={ (event) => { this._removeError("contacts.postal_address"); this._handle_onCheckboxFieldChange(event.target.name, parseInt(event.target.value, 10)); } } 
									disabled={ checking } 
								/>
								<label htmlFor="main.mail_delivery_address_type.fact" className="unselectable">По фактическому адресу, указанному в настоящей анкете</label>
							</div>

							<div className="form_field checkbox">
								<input type="radio" hidden="" 
									value={ 100000002 } 
									id="main.mail_delivery_address_type.postal" 
									name="main.mail_delivery_address_type" 
									checked={ parseInt(mail_delivery_address_type, 10) === 100000002 ? true : false } 
									onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, parseInt(event.target.value, 10)) } 
									disabled={ checking } 
								/>
								<label htmlFor="main.mail_delivery_address_type.postal" className="chackbox_with_margin unselectable" style={{ width: "100%" }}>
									<span>По следующему адресу { parseInt(mail_delivery_address_type, 10) === 100000002 && <sup className="required_label">*</sup> }</span>
									<AddressSuggests 
										className={ errors.indexOf("contacts.postal_address") > -1 ? "error" : "" } 
										value={ this._checkStrValue(postal_address.name) } 
										fias={ this._checkStrValue(postal_address.fias_id) } 
										onChange={ (data) => { this._removeError("contacts.postal_address"); this._handle_onTextFieldChange("contacts.postal_address", data); } } 
										required={ true } 
										disabled={ !checking && parseInt(mail_delivery_address_type, 10) === 100000002 ? false : true } 
									/>
								</label>
							</div>
						</div> 
					</div>

					{ !checking && (
						<div className="action">
							<button type="submit" className="button button-blue" onClick={ this._handle_onNextPage }>
								{ loading ? (
									<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" style={{ marginTop: "4px" }}/>
									) : "Продолжить" }
							</button>
							<button ref={ this.ref_submit } type="submit" style={{ display: "none" }}/>
							{ status !== "empty" && (
								<>
									<br/><br/>
									<a style={{ cursor: "pointer" }} onClick={ this._handle_onReset }>Отменить изменения в анкете</a>
								</>
							) }
						</div>
					) }
				</form>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		questionnaire: state.questionnaire, 
	}
}

export const getServerSideProps = reduxWrapper.getServerSideProps(store => 
	async ({ req, res, query }) => 
	{
    }
);

export default connect(mapStateToProps)(Form_2_Contacts);