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 pluralize from 'pluralize-ru';
import { SpinnerCircular } from 'spinners-react';
import NoSSR from "@mpth/react-no-ssr";

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

import InnerMenu from "../../components/questionnaire/InnerMenu";
import Header from '../components/Header';
import Footer from '../components/Footer';

import { sendPhoneChangeNumber, sendPhoneChangeNumberSmsCode, setUserPhone, getQuestionnaire, getContractGraphicChangeSignatories, getCompanyInfo, defaultQuestionnaire, } from '../../actions';
import AccountLayout from "../components/Layout/Account";
import Form_1_Main from "../../components/questionnaire/forms/Form_1_Main";
import Form_2_Contacts from "../../components/questionnaire/forms/Form_2_Contacts";
import Form_3_Signer from "../../components/questionnaire/forms/Form_3_Signer";
import Form_4_Shareholders from "../../components/questionnaire/forms/Form_4_Shareholders";
import Form_5_Regulatory from "../../components/questionnaire/forms/Form_5_Regulatory";
import Form_6_NonProfit from "../../components/questionnaire/forms/Form_6_NonProfit";
import Form_7_Check from "../../components/questionnaire/forms/Form_7_Check";
import Form_8_Signing from "../../components/questionnaire/forms/Form_8_Signing";
import Form_9_Status from "../../components/questionnaire/forms/Form_9_Status";

class QuestionnairePage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			phone: "", 
			phone_check_loading: false, 
			phone_number_format_error: false, 
			signatories: [], 
			company: {}, 
			nko: false, 
			moderation: false, 
			loading: true, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			signatories: nextProps.signatories, 
			company: nextProps.company, 
			nko: nextProps.nko, 
		};
	}

	componentDidMount()
	{
		const { dispatch } = this.props;

		getContractGraphicChangeSignatories({ dispatch });

		setTimeout(() => {
			this._init();
		}, 10);
	}

	_init = () => 
	{
		//console.log("_init");

		const { company } = this.state;
		const { dispatch } = this.props;

		//console.log("-".repeat(50));

		//console.log(company);


		getQuestionnaire({ dispatch, id: company.questionnaire_id })
		.then(() => 
		{
			this.setState({ loading: false, });
		})
		.catch(() => 
		{
			this.setState({ loading: false, moderation: true });
		});
	}

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

		return false;
	}

	_handle_onNextStep = (path) => 
	{
		//console.log("_handle_onNextStep", path);

		window.scrollTo(0, 0);
		this.props.router.push(`/questionnaire#${ path }`);
	}

	_handle_onSuccess = (sign) => 
	{
		//console.log("_handle_onSuccess");

		getCompanyInfo({ dispatch: this.props.dispatch });
		defaultQuestionnaire({ dispatch: this.props.dispatch, sign });
	}

	_renderForm = () => 
	{
		const { signatories, company } = this.state;
		const route = this.props.router.asPath;

		if (route.indexOf("#main") > -1) return (<Form_1_Main company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#contacts") > -1) return (<Form_2_Contacts company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#signer") > -1) return (<Form_3_Signer company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#shareholders") > -1) return (<Form_4_Shareholders company={ company } signatories={ signatories } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#regulatory") > -1) return (<Form_5_Regulatory company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#non-profit") > -1) return (<Form_6_NonProfit company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
		if (route.indexOf("#check") > -1) return (<Form_7_Check company={ company } signatories={ signatories } onNextStep={ this._handle_onNextStep } checking={ true }/>);
		if (route.indexOf("#signing") > -1) return (<Form_8_Signing onSuccess={ this._handle_onSuccess } onNextStep={ this._handle_onNextStep }/>);
		if (route.indexOf("#status") > -1) return (<Form_9_Status onSuccess={ this._handle_onSuccess } router={ this.props.router }/>);

		return (<Form_1_Main company={ company } onNextStep={ this._handle_onNextStep } checking={ false }/>);
	}

	render()
	{
		const { loading, moderation, company, nko, phone, phone_check_loading, phone_number_format_error } = this.state;
		const route = this.props.router.asPath;

		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>
					</div>
					<NoSSR>
						{ loading ? (
							<div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "center", }}>
								<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
							</div>									
						) : (
							<React.Fragment>
								{ moderation ? (
									<React.Fragment>
										<div className="questionnaire message moderate">
											<svg width="44" height="44" viewBox="0 0 44 44" fill="none" xmlns="http://www.w3.org/2000/svg">
												<path d="M22 38.5C31.1127 38.5 38.5 31.1127 38.5 22C38.5 12.8873 31.1127 5.5 22 5.5C12.8873 5.5 5.5 12.8873 5.5 22C5.5 31.1127 12.8873 38.5 22 38.5Z" fill="white"/>
												<path d="M23.0322 14.699L28.301 19.9678L29.0537 22.9785L25.2903 26.7419M14.0478 23.779L19.221 28.9522M18.957 29H14.7527C14.5531 29 14.3616 28.9207 14.2205 28.7795C14.0793 28.6384 14 28.4469 14 28.2473V24.043C14 23.9441 14.0195 23.8463 14.0573 23.7549C14.0951 23.6636 14.1506 23.5806 14.2205 23.5107L25.5107 12.2205C25.6519 12.0793 25.8433 12 26.043 12C26.2426 12 26.434 12.0793 26.5752 12.2205L30.7795 16.4248C30.9207 16.566 31 16.7574 31 16.957C31 17.1567 30.9207 17.3481 30.7795 17.4893L19.4893 28.7795C19.4194 28.8494 19.3364 28.9049 19.2451 28.9427C19.1537 28.9805 19.0559 29 18.957 29Z" stroke="#8E94A7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
											</svg>
											<p>
												<b>Анкета подписана и находится на проверке</b>
												При необходимости сотрудник Отдела по работе с клиентами свяжется с Вами.
											</p>
										</div>
										<div className="questionnaire status_action">
											<>
												<button className="button button-blue" style={{ width: "100%", minWidth: "255px" }} onClick={ () => this.props.router.push("/") }>Перейти на главную страницу </button>
											</>
										</div>
									</React.Fragment>
								) : (
									<div className={ `aside_container ${ route.indexOf("#status") < 0 ? "about" : "" }` }>
										{ route.indexOf("#status") < 0 && (
											<InnerMenu company={ company } nko={ nko } { ...this.props }/>
										) }
										<article>
											{ this._renderForm() }
										</article>
									</div>
								) }
							</React.Fragment>
						) }
					</NoSSR>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		company: state.company, 
		signatories: state.contract.change.signatories, 
		nko: state.questionnaire.main.nko, 
	}
}

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)(QuestionnairePage));