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 QuestionnaireForm from "../QuestionnaireForm";
import { reduxWrapper } from '../../../../store';
import { saveQuestionnaire } from "../../../../actions";
import FormMessage from "../FormMessage";

class Form_6_NonProfit extends QuestionnaireForm 
{
	constructor(props)
	{
		super(props);
		this.state = {
			non_profit: {
				fin_source_business: false, 
				fin_source_donate: false, 
				fin_source_fees: false, 
				fin_source_another: false, 
				fin_source_another_description: null, 
				foreign_payers: false, 
				fin_goals_cars: null, 
				fin_goals_trucks: null, 
				fin_goals_special: null, 
			}, 
			loading: false, 
			status: "empty", 
			errors: [], 
		};

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

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			non_profit: nextProps.questionnaire.non_profit, 
			status: nextProps.questionnaire.status, 
		};
	}

	componentDidMount()
	{
	}

	_handle_onFormSubmit = (event) => 
	{
		event.preventDefault();
		//console.log("Form_6_NonProfit", "_handle_onFormSubmit");


		this._handle_onCheckboxFieldChange("step", 7);
		setTimeout(() => 
		{
			saveQuestionnaire();
			this.props.onNextStep("check");
		}, 10);
	}

	_handle_onAnother = () => 
	{
		const { non_profit } = this.state;

		this._handle_onFieldChange("non_profit", { ...this.state.non_profit, ...{ 
			fin_source_another: !non_profit.fin_source_another ? true : false, 
			fin_source_another_description: non_profit.fin_source_another ? "" : non_profit.fin_source_another_description, 
		} });
	}

	_checkDisabled = () => 
	{
		const { non_profit } = this.state;
		const check = ["fin_goals_cars", "fin_goals_trucks", "fin_goals_special"];
		let need = true;

		for(let i in check)
		{
			if(non_profit[check[i]] !== null && non_profit[check[i]] !== "")
			{
				need = false;
			}
		}

		if(need)
		{
			return true;
		}

		if(non_profit.fin_source_another)
		{
			if(non_profit.fin_source_another_description === "")
			{
				return true;
			}
		}

		if(!non_profit.fin_source_business && !non_profit.fin_source_donate && !non_profit.fin_source_fees && !non_profit.fin_source_another)
		{
			return true;
		}

		return false;
	}

	_handle_onNextPage = (event) => 
	{
		//console.log("Form_6_NonProfit", "_handle_onNextPage");

		event.preventDefault();

		const { non_profit } = this.state;

		const errors = [];
		const fin_source = ["fin_source_business", "fin_source_donate", "fin_source_fees"];
		let check_another_fin_source = true;

		for(let i in fin_source)
		{
			if(non_profit[fin_source[i]] !== false)
			{
				check_another_fin_source = false;
			}
		}

		if(check_another_fin_source)
		{
			if(!non_profit.fin_source_another)
			{
				errors.push("non_profit.fin_source");
			}
			else
			{
				if(!this._checkStrNotEmpty(non_profit.fin_source_another_description))
				{
					errors.push("non_profit.fin_source_another_description");
				}
			}
		}

		const fin_goals = ["fin_goals_cars", "fin_goals_trucks", "fin_goals_special"];
		let fin_goals_need = true;

		for(let i in fin_goals)
		{
			if(this._checkStrNotEmpty(non_profit[fin_goals[i]]))
			{
				fin_goals_need = false;
			}
		}

		if(fin_goals_need)
		{
			errors.push("non_profit.fin_goals");
		}

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

	_checkRequired = (field) => 
	{
		const { non_profit } = this.state;
		const check = ["fin_goals_cars", "fin_goals_trucks", "fin_goals_special"];

		let need = true;

		for(let i in check)
		{
			if(non_profit[check[i]] !== null && non_profit[check[i]] !== "")
			{
				need = false;
			}
		}

		return need;
	}

	render()
	{
		const { checking } = this.props;
		const { non_profit, loading, status, errors } = this.state;

		//console.log("errors", errors);


		return (
			<React.Fragment>
				<form ref={ this.ref_form } onSubmit={ this._handle_onFormSubmit } onKeyDown={(e) => {if (e.key === 'Enter') e.preventDefault() }} className={`questionnaire questionnaire_6 ${ checking && "disabled" }`}>
					<p className="title">6. Данные о некомерческой организации</p>
					{ errors.indexOf("non_profit.fin_source") > -1 && 
					( 
						<FormMessage type="error" title="Ошибка" message="Необходимо указать источник происхождения денежных средств."/>
					) }
					<p>Источники происхождения денежных средств, из которых будут осуществляться лизинговые платежи:</p>

					<div className="form_field">
						<div style={{ width: "100%" }}>
							<div className="form_field checkbox">
								<input type="checkbox" hidden="" 
									id="non_profit.fin_source_business" 
									name="non_profit.fin_source_business" 
									checked={ non_profit.fin_source_business } 
									onChange={ (event) => { this._removeError("non_profit.fin_source"); this._handle_onCheckboxFieldChange(event.target.name, !non_profit.fin_source_business ? true : false); } } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.fin_source_business" className="unselectable">От приносящей доход деятельности</label>
							</div>
							<div className="form_field checkbox">
								<input type="checkbox" hidden="" 
									id="non_profit.fin_source_donate" 
									name="non_profit.fin_source_donate" 
									checked={ non_profit.fin_source_donate } 
									onChange={ (event) => { this._removeError("non_profit.fin_source"); this._handle_onCheckboxFieldChange(event.target.name, !non_profit.fin_source_donate ? true : false); } } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.fin_source_donate" className="unselectable">Добровольные пожертвования</label>
							</div>

							<div className="form_field checkbox">
								<input type="checkbox" hidden="" 
									id="non_profit.fin_source_fees" 
									name="non_profit.fin_source_fees" 
									checked={ non_profit.fin_source_fees } 
									onChange={ (event) => { this._removeError("non_profit.fin_source"); this._handle_onCheckboxFieldChange(event.target.name, !non_profit.fin_source_fees ? true : false ); } } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.fin_source_fees" className="unselectable">Вступительные членские взносы</label>
							</div>

							<div className="form_field checkbox">
								<input type="checkbox" hidden="" 
									id="non_profit.fin_source_another" 
									name="non_profit.fin_source_another" 
									checked={ non_profit.fin_source_another } 
									onChange={ (event) => { this._removeError([ "non_profit.fin_source", "non_profit.fin_source_another_description" ]); this._handle_onAnother(); } } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.fin_source_another" style={{ width: "100%" }} className="unselectable">
									<span>Иное { non_profit.fin_source_another && (<sup className="required_label">*</sup>) }</span>
									<input type="text" 
										className={ errors.indexOf("non_profit.fin_source_another_description") > -1 ? "error" : "" } 
										id="non_profit.fin_source_another_description" 
										name="non_profit.fin_source_another_description" 
										value={ this._checkStrValue(non_profit.fin_source_another_description) } 
										disabled={ checking ? true : non_profit.fin_source_another ? false : true } 
										placeholder="Укажите источник" 
										required={ non_profit.fin_source_another ? true : false } 
										onChange={ (event) => { this._removeError([ "non_profit.fin_source", "non_profit.fin_source_another_description" ]); this._handle_onTextFieldChange(event.target.name, event.target.value); } } 
									/>
								</label>
							</div>
						</div> 
					</div>

					<p>Организация является получателем денежных средств  и имущества от иностранных государств, международных  и иностранных организаций, иностранных граждан и лиц без гражданства:</p>

					<div className="form_field">
						<div style={{ width: "100%" }}>
							<div className="form_field checkbox">
								<input type="radio" hidden="" 
									value="0" 
									id="non_profit.foreign_payers_0" 
									name="non_profit.foreign_payers" 
									checked={ non_profit.foreign_payers === false ? true : false } 
									onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, false) } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.foreign_payers_0" className="unselectable">Нет</label>
							</div>
							<div className="form_field checkbox">
								<input type="radio" hidden="" 
									value="1" 
									id="non_profit.foreign_payers_1" 
									name="non_profit.foreign_payers" 
									checked={ non_profit.foreign_payers === false ? false : true } 
									onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, true) } 
									disabled={ checking } 
								/>
								<label htmlFor="non_profit.foreign_payers_1" className="unselectable">Да</label>
							</div>
						</div> 
					</div>

					{ errors.indexOf("non_profit.fin_goals") > -1 && 
					( 
						<FormMessage type="error" title="Ошибка" message="Необходимо указать цели использования предмета лизинга для любой из категорий."/>
					) }
					<p>Укажите цели использования предмета лизинга и подтвердите их соответствие уставным целям для каждого предмета лизинга отдельно</p>

					<div className="form_field">
						<label className="unselectable">Легковые автомобили</label>
						<input type="text" 
							id="non_profit.fin_goals_cars" 
							name="non_profit.fin_goals_cars" 
							value={ this._checkStrValue(non_profit.fin_goals_cars) } 
							placeholder="Введите данные" 
							onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, event.target.value) } 
							required={ false } 
							disabled={ checking } 
						/>
					</div>

					<div className="form_field">
						<label className="unselectable">Легкий коммерческий транспорт</label>
						<input type="text" 
							id="non_profit.fin_goals_trucks" 
							name="non_profit.fin_goals_trucks" 
							value={ this._checkStrValue(non_profit.fin_goals_trucks) } 
							placeholder="Введите данные" 
							onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, event.target.value) } 
							required={ false } 
							disabled={ checking } 
						/>
					</div>

					<div className="form_field">
						<label className="unselectable">Грузовые автомобили/ спецтехника</label>
						<input type="text" 
							id="non_profit.fin_goals_special" 
							name="non_profit.fin_goals_special" 
							value={ this._checkStrValue(non_profit.fin_goals_special) } 
							placeholder="Введите данные" 
							onChange={ (event) => this._handle_onCheckboxFieldChange(event.target.name, event.target.value) } 
							required={ false } 
							disabled={ checking } 
						/>
					</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_6_NonProfit);