import React from "react";
import { SpinnerCircular } from 'spinners-react';
import { GoogleReCaptchaProvider, GoogleReCaptcha, withGoogleReCaptcha } from 'react-google-recaptcha-v3';

import { sendLeasingOrder } from "../../../actions";

class FormContent extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			name: "", 
			phone: "", 
			email: "", 
			company: "", 
			accept: true, 
			success: false, 
			fail: false, 
			leasing_form_submitting: false, 
			errors: {}, 
		};
	}

	isEmail = (email) => 
	{
		var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return regex.test(email);
	}

	checkErrors = () => 
	{
		let valid = true;
		let errors = {};

		const { name, phone, email } = this.state;

		if(name === "")
		{
			valid = false;
			errors['name'] = "Необходимо указать Ваши ФИО";
		}

		if(phone === "")
		{
			valid = false;
			errors['phone'] = "Необходимо указать номер Вашего телефона";
		}

		if(email === "")
		{
			valid = false;
			errors['email'] = "Необходимо указать Ваш адрес E-mail";
		}
		else
		{
			if(!this.isEmail(email))
			{
				valid = false;
				errors['email'] = "Пожалуйста, укажите правильный адрес E-mail";
			}	
		}

		this.setState({ errors: errors });

		return valid;
	}

	_onFormSubmit = (event) => 
	{
		event.preventDefault();
		const { accept, leasing_form_submitting } = this.state;

		if(accept && !leasing_form_submitting && this.checkErrors())
		{
			const { executeRecaptcha } = this.props.googleReCaptchaProps;

			this.setState({ leasing_form_submitting: true }, () => 
			{
				executeRecaptcha()
				.then((token) => 
				{
					sendLeasingOrder({ ...this.state, ...{ recaptcha_token: token } })
					.then(() => 
					{
						this.setState({ leasing_form_submitting: false, success: true, fail: false });
					})
					.catch((response) => 
					{
						if(response.message === "recaptcha_error")
						{
							this.setState({ leasing_form_submitting: false, success: false, fail: true });
						}
						else
						{
							this.setState({ leasing_form_submitting: false, success: false, fail: false });
						}
					});
				})
				.catch((error) => 
				{
					console.error("error", error);
					this.setState({ leasing_form_submitting: false });
				});
			});
		}
	}

	_handle_onChange_name = (value) => 
	{
		const errors = { ...this.state.errors };
		errors.name = undefined;

		this.setState({ name: value, errors: errors });
	}

	_handle_onChange_phone = (value) => 
	{
		const errors = { ...this.state.errors };
		errors.phone = undefined;

		this.setState({ phone: value, errors: errors });
	}

	_handle_onChange_email = (value) => 
	{
		const errors = { ...this.state.errors };
		errors.email = undefined;

		this.setState({ email: value, errors: errors });
	}

	_handle_onChange_accept = (accept) => 
	{
		console.log(accept);
		this.setState({ accept: accept });
	}

	_handle_onPersonaData = () => 
	{
		window.open(`${ process.env.NEXT_PUBLIC_MAIN_SITE }/personal_data/`, "_blank");
	}

	render()
	{
		const { name, phone, email, company, accept, success, fail, errors, leasing_form_submitting } = this.state;

		return (
			<section id="order">
				<div className="container wide">
					<h2 className="section_title">Купить в лизинг?</h2>
					<div className="order_form">
						<div className="order_email">
							<p>Напишите на <a href="mailto:">buy@evoleasing.ru</a> или заполните форму</p>
						</div>
						<form onSubmit={ (event) => this._onFormSubmit(event) } style={ !fail ? {} : { backgroundColor: "#2C2D2E" }}>
							{ !success ? !fail ? (
								<>
									<div className={`form_field ${ errors['name'] !== undefined ? 'error' : '' }`} data-error={ errors['name'] !== undefined ? errors['name'] : null }>
										<input type="text" value={ name } placeholder="Имя" onChange={ (event) => this._handle_onChange_name(event.target.value) }/>
									</div>
									<div className={`form_field ${ errors['phone'] !== undefined ? 'error' : '' }`} data-error={ errors['phone'] !== undefined ? errors['phone'] : null }>
										<input type="tel" value={ phone } placeholder="Телефон" onChange={ (event) => this._handle_onChange_phone(event.target.value) }/>
									</div>
									<div className={`form_field ${ errors['email'] !== undefined ? 'error' : '' }`} data-error={ errors['email'] !== undefined ? errors['email'] : null }>
										<input type="text" value={ email } placeholder="E-mail" onChange={ (event) => this._handle_onChange_email(event.target.value) }/>
									</div>
									<div className={`form_field ${ errors['company'] !== undefined ? 'error' : '' }`}>
										<input type="text" value={ company } placeholder="Организация" onChange={ (event) => this.setState({ company: event.target.value }) }/>
									</div>
									<div className="policy">
										<input type="checkbox" name="policy" id="policy" hidden checked={ accept } onChange={ (event) => this._handle_onChange_accept(event.target.checked) }/>
										<label htmlFor="policy">Даю свое согласие на обработку {`\u00A0`}<u onClick={ () => this._handle_onPersonaData() }>моих персональных данных</u></label>
									</div>
									<button className="button" disabled={ !accept } style={{ minWidth: "100px" }}>
										{ leasing_form_submitting ? (
											<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" style={{ marginTop: "4px" }}/>
										) : "Отправить" }
									</button>
									<div style={{ position: "absolute", left: "10px", bottom: "9px", fontSize: "9px", color: "#FFF", opacity: "0.5", lineHeight: "11px" }}>защита от спама reCAPTCHA<br/><a href="https://policies.google.com/privacy" target="_blank" style={{ fontSize: "9px", color: "#FFF", textDecoration: "underline" }}>Конфиденциальность</a> - <a href="https://policies.google.com/terms" target="_blank" style={{ fontSize: "9px", color: "#FFF", textDecoration: "underline" }}>Условия использования</a></div>
								</>
							) : (<>
									<div style={{ minHeight: "400px", alignItems: "center", justifyContent: "center", display: "flex" }}>
										<p style={{ color: "#fff", fontSize: "24px", lineHeight: "34px" }}>Сожалеем, запросы, отправляемые с Вашего устройства похожи на автоматические. Пожалуйста, воспользуйтесь другим браузером/подключением или попробуйте позднее.</p>
									</div>
								</>
							) : (
								<div style={{ minHeight: "400px", alignItems: "center", justifyContent: "center", display: "flex" }}>
									<p style={{ color: "#fff", fontSize: "24px", lineHeight: "34px" }}>Благодарим Вас за обращение, наши специалисты свяжутся с Вами в ближайшее время.</p>
								</div>
							) }
						</form>
					</div>
				</div>
			</section>
		)
	}
}

export const FormContentWithRecaptcha = withGoogleReCaptcha(FormContent);

export default class FormRequest extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
		};
	}

	render()
	{
		return (
			<GoogleReCaptchaProvider reCaptchaKey={ process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY }>
				<FormContentWithRecaptcha/>
			</GoogleReCaptchaProvider>
		)
	}
}

/*
export default class FormRequest extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			recaptcha_token: null, 
		};
	}

	componentDidMount()
	{
		setTimeout(() => 
		{
			this.setState({ recaptcha_token: null });
		}, 120000);
	}

	render()
	{
		const { recaptcha_token } = this.state;

		return (
			<GoogleReCaptchaProvider reCaptchaKey={ process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY }>
				{ recaptcha_token === null && (
					<GoogleReCaptcha onVerify={ (token) => { console.log("GoogleReCaptcha", "token response", token); this.setState({ recaptcha_token: token })} }/>
				) }
				<FormContent recaptcha_token={ recaptcha_token }/>
			</GoogleReCaptchaProvider>
		)
	}
}
*/