import React from "react";
import Head from 'next/head';
import Image from 'next/image';
import Link from "next/link";
import cookie from 'cookie';
import { connect } from "react-redux";
import numeral from "numeral";
import { SpinnerCircular } from 'spinners-react';

import { withRouter } from 'next/router';
import { reduxWrapper } from '../../store';

import InnerMenu from "./components/InnerMenu";
import Header from '../components/Header';
import Footer from '../components/Footer';
import Pagination from '../components/Pagination';
import Company from "../components/Company";

import { sendNewPassword } from '../../actions';
import AccountLayout from "../components/Layout/Account";

class IndexPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			password_form_step: 1, 
			password: "", 
			password_error: false, 
			new_password: "", 
			new_password_repeat: "", 
			new_password_check_loading: false, 
			new_password_submit_disabled: true, 
			new_password_error: false, 
			user: {}, 
			observer: false, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			observer: nextProps.observer, 
			user: nextProps.user, 
		};
	}

	componentDidMount()
	{
	}

	componentWillUnmount()
	{
	}

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

		const { password, new_password, new_password_repeat, new_password_check_loading, user, } = this.state;

		if(!new_password_check_loading)
		{
			this.setState({ new_password_check_loading: true }, () => 
			{
				sendNewPassword({ email: user.email, password, new_password, new_password_repeat, })
				.then((response) => 
				{
					if(response.status === "success")
					{						
						this.setState({ new_password_error: false, new_password_check_loading: false, password_form_step: 2, });
					}
					else
					{
						console.log(response.error);
						if(response.status === "error" && response.error === "wrong_email")
						{
							this.setState({ password_error: true, new_password_error: false, new_password_check_loading: false });
						}
					}
				})
				.catch(() => 
				{
					this.setState({ new_password_error: true, new_password_check_loading: false });
				});	
			});
		}
	}

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

	_handle_onNewPasswordChange = (value) => 
	{
		let error = false;
		if(this.state.new_password_repeat.length > 0)
		{
			value === this.state.new_password ? false : true;
			error = value.length < 6 ? true : error;
		}

		this.setState({ new_password: value, new_password_submit_disabled: this._check_fields_disabled([ value, this.state.password, this.state.new_password_repeat ]), new_password_error: false });
	}

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

		this.setState({ new_password_repeat: value, new_password_submit_disabled: error ? true : this._check_fields_disabled([ value, this.state.password, this.state.new_password ]), new_password_error: error });
	}

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

		return false;
	}

	render()
	{
		console.log("this.state.user", this.state.user);
		const { user, observer, password, password_error, new_password, new_password_repeat, new_password_submit_disabled, new_password_check_loading, new_password_error, password_form_step } = this.state;

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta
						name="description"
						content="ЛК Эволюция автолизинга"
					/>
				</Head>
				<Header { ...this.props }/>
				<AccountLayout>
					<div className="title_wrapper">
						<div className="left">
							<h1 className="section_title">Смена пароля</h1>
						</div>
						<Company { ...this.props }/>
					</div>
					<div className="aside_container about">
						<InnerMenu { ...this.props } user={ user } observer={ observer }/>
						<article>
							{ password_form_step === 1 && (
								<div className={`login recovery`}>
									<form onSubmit={ this._handle_onPasswordSubmit } className="newPass_form">
										<p className="message full">Введите Ваш текущий пароль</p>
										<div className="form_field">
											<input type="password" name="password" value={ password } placeholder="Текущий пароль" onChange={ (event) => this._handle_onPasswordChange(event.target.value) } />
										</div>
										<p style={{ width: "100%" }}>{ password_error ? 'Ошибка: неверный пароль' : `\u00A0` }</p>
										<p style={{ width: "100%" }} className="message"><br/></p>
										<p style={{ width: "100%" }} className="message"><br/></p>
										<p className="message full">Введите новый пароль и повторите новый пароль</p>
										<div className="form_field">
											<input type="password" name="new_password" value={ new_password } placeholder="Новый пароль" onChange={ (event) => this._handle_onNewPasswordChange(event.target.value) } />
										</div>
										<div className="form_field">
											<input type="password" name="new_password_repeat" value={ new_password_repeat } placeholder="Новый пароль (повторите)" onChange={ (event) => this._handle_onNewPasswordRepeatChange(event.target.value) } />
										</div>
										<button type="submit" className="button button-blue" disabled={ new_password_submit_disabled }>
											{ new_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 className="full">{ new_password_error ? 'Внимание: пароли не совпадают' : `\u00A0` }</p>
									<p className="full">{ new_password.length < 6 ? 'Внимание: минимальная длина пароля - 6 символов' : `\u00A0` }</p>
								</div>
							) }
							{ password_form_step === 2 && (
								<div className={`login recovery`}>
									<p className="message full">Ваш пароль был успешно изменен.</p>
								</div>
							) }
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		observer: state.auth.observer, 
		user: state.user, 
	}
}

export const getServerSideProps = reduxWrapper.getServerSideProps(store => 
	async ({ req, res, query }) => 
	{
		let props = {};

		if(req.headers.cookie !== undefined)
		{
			const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

			if(cookies.jwt === undefined || cookies.jwt === null)
			{
				res.statusCode = 302;
				res.setHeader('Location', `/login`);
			}
			else
			{
				//const tokenValid = await checkToken(cookies.jwt);
				const tokenValid = true;
				if(!tokenValid)
				{
					res.statusCode = 302;
					res.setHeader('Location', `/login`);
				}
			}
		}
		else
		{
			res.statusCode = 302;
			res.setHeader('Location', `/login`);
		}
	
		return { props: props };
	}
);

export default withRouter(connect(mapStateToProps)(IndexPage));