import React from "react";

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

export default class FormRequest extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			name: "", 
			phone: "", 
			email: "", 
			company: "", 
			accept: true, 
			success: 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())
		{
			this.setState({ leasing_form_submitting: true }, () => 
			{
				sendLeasingOrder(this.state)
				.then(() => 
				{
					this.setState({ leasing_form_submitting: false, success: true });
				})
				.catch(() => 
				{
					this.setState({ leasing_form_submitting: false, success: 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, errors } = 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) }>
							{ !success ? (
								<>
									<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 }>Отправить</button>
								</>
							) : (
								<div style={{ minHeight: "400px", alignItems: "center", justifyContent: "center", display: "flex" }}>
									<p style={{ color: "#fff", fontSize: "24px", lineHeight: "34px" }}>Благодарим Вас за обращение, наши специалисты свяжутся с Вами в ближайшее время.</p>
								</div>
							) }
						</form>
					</div>
				</div>
			</section>
		)
	}
}