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 { connect } from "react-redux";
import { withRouter } from 'next/router';
import InputMask from 'react-input-mask';
import CurrencyInput from 'react-currency-input-field';

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

class Form_1_Main extends QuestionnaireForm 
{
	constructor(props)
	{
		super(props);
		this.state = {
			main: {
				title: null, 
				inn: null, 
				kpp: null, 
				email: null, 
				telephone: null, 
				websiteurl: null, 
				financial_loan: null, 
				is_individual_executive: false, 
				individual_executive_inn: "", 
				individual_executive_kpp: "", 
				individual_executive_oop: "", 
				individual_executive_docnum: "", 
				individual_executive_docdate: "", 
				high_level: "", 
				board_of_directors: "", 
				collective_executive: "", 
				individual_executive: "", 
				other_control: "", 
				nko: false, 
				accept: false, 
			}, 
			non_profit_template: {
				fin_source_business: false, 
				fin_source_donate: false, 
				fin_source_fees: false, 
				fin_source_another: false, 
				fin_source_another_description: "", 
				foreign_payers: false, 
				fin_goals_cars: "", 
				fin_goals_trucks: "", 
				fin_goals_special: "", 
			}, 
			licenses: null, 
			step: 1, 
			status: "empty", 
			loading: false, 
			errors: [], 
		};

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

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

	componentDidMount()
	{
		const { licenses } = this.state;
		//if(licenses !== null && licenses !== undefined && licenses !== "")
		//{
			this.ref_licenses_field.current.style.height = (this.ref_licenses_field.current.scrollHeight + 10) + "px";
		//}
	}

	componentDidUpdate(prevProps, prevState)
	{
		if(this.ref_licenses_field.current.scrollHeight - parseInt(this.ref_licenses_field.current.style.height, 10) > 6)
		{
			this.ref_licenses_field.current.style.height = (this.ref_licenses_field.current.scrollHeight + 6) + "px";
		}
		else
		{
			if(this.ref_licenses_field.current.scrollHeight - parseInt(this.ref_licenses_field.current.style.height, 10) > 6)
			{
				this.ref_licenses_field.current.style.height = (this.ref_licenses_field.current.scrollHeight + 6) + "px";
			}	
		}
	}

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

		const errors = [];

		const { main } = this.state;
		const { company } = this.props;
		const check = ["title", "inn", "kpp", "email", "telephone", "financial_loan"];

		if(company.inn.length > 10)
		{
			check.splice(check.indexOf("kpp"), 1);
		}

		for(let i in check)
		{
			if(check[i] === "telephone")
			{
				if(main.telephone === "" || main.telephone === null || isNaN(parseInt(main.telephone.replace(/[^\d]+/g, ''), 10)) || parseInt(main.telephone.replace(/[^\d]+/g, ''), 10).toString().length < 11)
				{
					errors.push(`main.telephone`);
				}
			}
			else
			{
				if(main[check[i]] === null || main[check[i]] === "")
				{
					errors.push(`main.${ check[i] }`);
				}	
			}	
		}

		if(main.websiteurl !== null && main.websiteurl !== "")
		{
			const r = new RegExp('^(http:\/\/|https:\/\/)?[A-zА-я0-9][A-zА-я0-9-]{1,61}[A-zА-я0-9](?:\.[A-zА-я]{2,})+', 'g');
			if(!r.test(main.websiteurl))
			{
				errors.push(`main.websiteurl`);
			}
		}		

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

	_handle_onNonProfitChange = () => 
	{
		const { main, non_profit_template, step } = this.state;

		this._handle_onFieldChange("non_profit", JSON.parse(JSON.stringify(non_profit_template)));
		this._handle_onCheckboxFieldChange("main.nko", !main.nko ? true : false);

		if(step > 6)
		{
			this._handle_onFieldChange("step", 6);
		}
	}

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

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

	_check_fields_disabled = (values) => 
	{
		for(let i in values)
		{
			if(values[i] === "")
			{
				return true;
			}
		}

		return false;
	}

	render()
	{
		const { company, checking } = this.props;
		const { loading, main, licenses, status, errors, } = this.state;
		const firstLetter = /(?!.*[DFIOQU])[A-VXY]/i;
		const letter = /(?!.*[DFIOQU])[A-Z]/i;
		const digit = /[0-9]/;
		const fin_mask = [firstLetter, digit, letter, " ", digit, letter, digit];

		return (
			<React.Fragment>
				<form ref={ this.ref_form } onSubmit={ this._handle_onFormSubmit } onKeyDown={(e) => {if (e.key === 'Enter') e.preventDefault() }} className={`questionnaire questionnaire_1 ${ checking && "disabled" }`}>
					<p className="title">1. Информация о лизингополучателе</p>
					{ errors.length > 0 &&
					( 
						<FormMessage type="error" title="Ошибка" message="Пожалуйста, проверьте корректность заполнения данных в форме."/>
					) }
					<div className="form_field">
						<label>Краткое наименование <sup className="required_label">*</sup></label>
						<input type="text" 
							className={ errors.indexOf("main.title") > -1 ? "error" : "" } 
							id="main.title" 
							name="main.title" 
							value={ this._checkStrValue(main.title) } 
							placeholder="Введите наименование" 
							onChange={ (event) => { this._removeError("main.title"); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
							required={ true } 
							disabled={ true } 
						/>
					</div>

					<div className="formgroup">
						<div className="form_field">
							<label>ИНН <sup className="required_label">*</sup></label>
							<input type="text" 
								className={ errors.indexOf("main.inn") > -1 ? "error" : "" } 
								id="main.inn" 
								name="main.inn" 
								value={ this._checkStrValue(main.inn) } 
								placeholder="Введите ИНН" 
								onChange={ (event) => { this._removeError("main.inn"); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
								required={ true } 
								disabled={ true } 
								maxLength={ 12 } 
							/>
						</div>
						{ company.inn.length < 11 && (
							<div className="form_field">
								<label>КПП <sup className="required_label">*</sup></label>
								<input type="text" 
									className={ errors.indexOf("main.kpp") > -1 ? "error" : "" } 
									id="main.kpp" 
									name="main.kpp" 
									value={ this._checkStrValue(main.kpp) } 
									placeholder="Введите КПП" 
									onChange={ (event) => { this._removeError("main.kpp"); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
									required={ true } 
									disabled={ true } 
								/>
							</div>
						) }
					</div>

					<div className="formgroup">
						<div className="form_field">
							<label>Телефон <sup className="required_label">*</sup></label>
							<InputMask 
								className={ errors.indexOf("main.telephone") > -1 ? "error" : "" } 
								mask='+7 (999) 999 99 99' 
								id="main.telephone" 
								name="main.telephone" 
								value={ this._checkStrValue(main.telephone) } 
								placeholder="Введите номер" 
								onChange={ (event) => { if(event.target.value !== "" && !isNaN(parseInt(event.target.value.replace(/[^\d]+/g, ''), 10)) && parseInt(event.target.value.replace(/[^\d]+/g, ''), 10) > 7) { this._removeError("main.telephone"); } this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
								required={ true } 
								disabled={ checking }>
							</InputMask>
						</div>

						<div className="form_field">
							<label>Сайт<small>Опционально</small></label>
							<input type="text" 
								className={ errors.indexOf("main.websiteurl") > -1 ? "error" : "" } 
								id="main.websiteurl" 
								name="main.websiteurl" 
								value={ this._checkStrValue(main.websiteurl) } 
								placeholder="Например https://example.com" 
								onChange={ (event) => { this._removeError(event.target.name); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
								disabled={ checking } 
								//pattern="[A-zА-я0-9\-]+"
								pattern="^(http:\/\/|https:\/\/)?[A-zА-я0-9][A-zА-я0-9\-]{1,61}[A-zА-я0-9](?:\.[A-zА-я]{2,})+"
							/>
						</div>
					</div>

					<div className="form_field">
						<label>E-mail <sup className="required_label">*</sup></label>
						<input type="email" 
							className={ errors.indexOf("main.email") > -1 ? "error" : "" } 
							id="main.email" 
							name="main.email" 
							value={ this._checkStrValue(main.email) } 
							placeholder="Укажите адрес электронной почты" 
							onChange={ (event) => { this._removeError("main.email"); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
							required={ true } 
							disabled={ checking } 
						/>
						<p>может использоваться для отправки лизингодателем юридически значимых сообщений в соответсвии с условиями договора лизинга, а так же для операций в электронном ПТС/ПСМ</p>
					</div>

					<div className="form_field">
						<label>Финансовая нагрузка <sup className="required_label">*</sup></label>
						 <CurrencyInput 
						 	className={ errors.indexOf("main.financial_loan") > -1 ? "error" : "" } 
							id="main.financial_loan" 
							name="main.financial_loan" 
							value={ this._checkStrValue(main.financial_loan) !== "" && parseFloat(main.financial_loan) > 0 ? this._checkStrValue(main.financial_loan) : null } 
							decimalsLimit={ 2 } 
							//selectAllOnFocus={ true } 
							placeholder="Укажите сумму" 
							decimalSeparator="." 
							groupSeparator=" " 
							//suffix=" ₽" 
							maxLength={ 12 } 
							onValueChange={ (value, name) => { this._removeError(name); this._handle_onTextFieldChange(name, value); } } 
							required={ true } 
							disabled={ checking } 
						 />
						<p>сумма текущих ежемесячных платежей по действующим кредитам/договорам лизинга</p>
					</div>

					<div className="form_field" style={{ alignItems: "flex-start" }}>
						<label>Информация о лицензиях</label>
						<textarea 
							style={{ fontSize: "14px" }} 
							ref={ this.ref_licenses_field } 
							className={ errors.indexOf("licenses") > -1 ? "error" : "" } 
							id="licenses" 
							name="licenses" 
							placeholder="Укажите, если деятельность подлежит лицензированию" 
							onChange={ (event) => { this._removeError("licenses"); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
							required={ true } 
							disabled={ checking } 
							defaultValue={ this._checkStrValue(licenses) }
						/>
					</div>

					{ company.inn.length < 11 && (
						<div className="form_field">
							<label><b>Организация является НКО</b></label>
							<div>
								<div className="form_field checkbox">
									<input type="radio" 
										checked={ !main.nko } 
										hidden="" 
										id="main.nko_0" 
										name="main.nko" 
										onChange={ (event) => this._handle_onNonProfitChange() } 
										disabled={ main.nko && checking } 
									/>
									<label htmlFor="main.nko_0" className="unselectable">Нет</label>
								</div>
								<div className="form_field checkbox">
									<input type="radio" 
										checked={ main.nko } 
										hidden="" 
										id="main.nko_1" 
										name="main.nko" 
										onChange={ (event) => this._handle_onNonProfitChange() } 
										disabled={ !main.nko && checking } 
									/>
									<label htmlFor="main.nko_1" className="unselectable">Да</label>
								</div>
							</div>
						</div>
					) }

					{ !checking && (
						<div className="action" style={{ flexDirection: "column" }}>
							<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_1_Main);