import React from "react";
import Head from 'next/head';
import Link from "next/link";
import Image from 'next/image';
import { connect } from "react-redux";
import { withRouter } from 'next/router';
import { reduxWrapper } from '../store';
import pluralize from 'pluralize-ru';
import { SpinnerCircular } from 'spinners-react';

import Header from './components/Header';
import Footer from './components/Footer';
import MainHeader from "./components/MainHeader";
import FormRequest from "./components/FormRequest";

import { sendEmailCheck, sendEmailCode, sendPassword } from "../actions/recoveryActions";

export default class RecoveryPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			email: "", 
			email_code: "", 
			password: "", 
			password_repeat: "", 
			tab: "email", 
			email_error: false, 
			recovery_form_step: 1, 
			email_code_error: false, 
			email_send_disabled: false, 
			set_password_disabled: true, 
			email_code_submit_disabled: true, 
			email_code_resend_disabled: true, 
			timer: 0, 
			email_auth_loading: false, 
			email_check_loading: false, 
			code_check_loading: false, 
			password_check_loading: false, 
			password_submit_disabled: true, 
			password_error: false, 
		};

		this.timer_ref = null;
	}

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

		const { email, email_check_loading } = this.state;

		if(!email_check_loading)
		{
			this.setState({ email_check_loading: true }, () => 
			{
				sendEmailCheck({ email })
				.then(() => 
				{
					this.setState({ email_check_loading: false, email_error: false, timer: 60, recovery_form_step: 2, }, () => 
					{
						this.timer_ref = setInterval(() => 
						{
							const t = this.state.timer - 1;
							this.setState({ timer: t, }, () => 
							{
								if(t === 0)
								{
									clearInterval(this.timer_ref);
								}
							});
						}, 1000);
					});
				})
				.catch(() => 
				{
					this.setState({ email_error: true, email_check_loading: false });
				});
			});
		}
	}

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

		const { email, email_code, code_check_loading } = this.state;

		if(!code_check_loading)
		{
			this.setState({ code_check_loading: true }, () => 
			{
				sendEmailCode({ email, code: email_code })
				.then(() => 
				{
					this.setState({ email_code_error: false, code_check_loading: false, recovery_form_step: 3, });
				})
				.catch(() => 
				{
					this.setState({ email_code_error: true, code_check_loading: false });
				});	
			});
		}
	}

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

		const { email, email_code, password, password_repeat, password_check_loading, } = this.state;

		if(!password_check_loading)
		{
			this.setState({ password_check_loading: true }, () => 
			{
				sendPassword({ email, code: email_code, password, password_repeat, })
				.then(() => 
				{
					this.setState({ password_error: false, password_check_loading: false, recovery_form_step: 4, });
				})
				.catch(() => 
				{
					this.setState({ password_error: true, password_check_loading: false });
				});	
			});
		}
	}

	_handle_onResendEmailCode = (event) => 
	{
		this.setState({ email_code_error: false }, () => 
		{
			this._handle_onEmailSubmit(event);
		});
	}

	_handle_onEmailChange = (value) => 
	{
		this.setState({ email: value, email_send_disabled: this._check_fields_disabled([ value, this.state.email ]), email_error: false });
	}

	_handle_onPasswordChange = (value) => 
	{
		this.setState({ password: value, set_password_disabled: this._check_fields_disabled([ value, this.state.password ]), password_error: false });
	}

	_handle_onPasswordCheckChange = (value) => 
	{
		this.setState({ password_repeat: value, set_password_disabled: this._check_fields_disabled([ value, this.state.password_repeat ]), password_error: false });
	}

	_handle_onEmailCodeChange = (value) => 
	{
		this.setState({ email_code: value, email_code_submit_disabled: this._check_fields_disabled([ value ]), email_code_error: false });
	}

	_handle_onPasswordChange = (value) => 
	{
		let error = value === this.state.password_repeat ? false : true;
		error = value.length < 6 ? true : error;

		this.setState({ password: value, password_submit_disabled: error ? true : this._check_fields_disabled([ value ]), password_error: error });
	}

	_handle_onPasswordRepeatChange = (value) => 
	{
		let error = value === this.state.password ? false : true;
		error = value.length < 6 ? true : error;

		this.setState({ password_repeat: value, password_submit_disabled: error ? true : this._check_fields_disabled([ value ]), password_error: error });
	}

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

		return false;
	}

	render()
	{
		const { email, email_code, tab, email_error, email_code_error, 
			set_password_disabled, email_send_disabled, recovery_form_step, email_code_submit_disabled, email_code_resend_disabled, 
			timer, email_auth_loading, email_check_loading, code_check_loading, 
			password, password_repeat, password_submit_disabled, password_check_loading, password_error } = this.state;

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta
						name="description"
						content="ЛК Эволюция автолизинга"
					/>
				</Head>
				<MainHeader logo_url={ process.env.NEXT_PUBLIC_MAIN_SITE } />
				<main>
					<section>
						<div className="clear"></div>
						<div className="container">
							<h1 className="section_title">Восстановление пароля</h1>
							<div className="login recovery">
								<div className="login_with">
									<p>Восстановить с помощью</p>
									<div className="tabs">
										<div className="tab active">Электронной почты</div>
									</div>
								</div>
								{ recovery_form_step === 1 && (
									<>
										<form onSubmit={ this._handle_onEmailSubmit }>
											<div className="form_field">
												<input type="text" name="email" value={ email } placeholder="Введите адрес E-mail" onChange={ (event) => this._handle_onEmailChange(event.target.value) } required={ true }/>
											</div>
											<button type="submit" className="button button-blue" disabled={ email_send_disabled }>
												{ email_auth_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>
										</form>
										<p>{ email_error ? 'Ошибка: Неверный адрес E-mail' : `\u00A0` }</p>
									</>
								) }
								{ recovery_form_step === 2 && (
									<>
										<p className="message">На адрес E-mail <strong>{ email }</strong> отправлен код подтверждения.</p>
										<form onSubmit={ this._handle_onCodeSubmit }>
											<div className="form_field">
												<input type="text" name="email_code" value={ email_code } placeholder="Введите код из письма" onChange={ (event) => this._handle_onEmailCodeChange(event.target.value) } />
											</div>
											<button type="submit" className="button button-blue" disabled={ email_code_submit_disabled }>
												{ code_check_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>
										</form>
										<div className="resend" style={{ justifyContent: "flex-start" }}>
											{ timer !== 0 ? (
												<p>Запросить код повторно можно через: { timer } { pluralize(timer, 'секунд', 'секунду', 'секунды', 'секунд') }</p>
											) : (
												<button className="button button-blue transparent" onClick={ (event) => this._handle_onResendEmailCode(event) }>Запросить код повторно</button>
											) }
											{/* disabled={ email_code_resend_disabled }*/}
										</div>
										<p>{ email_code_error ? 'Ошибка: Вы указали неверный код' : `\u00A0` }</p>
									</>
								) }
								{ recovery_form_step === 3 && (
									<>
										<p className="message">Вы указали верный код. Введите новый пароль и повторите новый пароль</p>
										<form onSubmit={ this._handle_onPasswordSubmit } className="newPass_form">
											<div className="form_field">
												<input type="password" name="password" value={ password } placeholder="Введите новый пароль" onChange={ (event) => this._handle_onPasswordChange(event.target.value) } />
											</div>
											<div className="form_field">
												<input type="password" name="password_repeat" value={ password_repeat } placeholder="Повторите новый пароль" onChange={ (event) => this._handle_onPasswordRepeatChange(event.target.value) } />
											</div>
											<button type="submit" className="button button-blue" disabled={ password_submit_disabled }>
												{ password_check_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>
										</form>
										<p>{ password_error ? 'Внимание: пароли не совпадают' : `\u00A0` }</p>
										<p>{ password.length < 6 ? 'Внимание: минимальная длина пароля - 6 символов' : `\u00A0` }</p>
									</>
								) }
								{ recovery_form_step === 4 && (
									<>
										<p className="message">Поздравляем, пароль успешно изменен. <Link href="/login"><a style={{ cursor: "pointer" }}>Нажмите здесь для авторизации</a></Link>.</p>
									</>
								) }
							</div>
						</div>
					</section>
					<FormRequest/>
				</main>
				<Footer authenticated={ false }/>
			</React.Fragment>
		)
	}
}