import React from "react";
import Head from 'next/head';
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 { sendOffstageToken, sendSwitchAccount } from '../actions';

class SwitchPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			error: undefined, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
		};
	}

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

		sendSwitchAccount({ dispatch, acc_number: this.props.account })
		.then(() => 
		{
			this.setState({ error: false });
		})
		.catch(() => 
		{
			this.setState({ error: true });
		});	
	}

	render()
	{
		const { 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" style={{ width: "100vw", height: "80vh", display: "flex", alignItems: "center", justifyContent: "center", }}>
							{ error === true ? (
								<p>Предоставленный токен невалиден или аккаунт не найден</p>
							) : (
								<SpinnerCircular size={90} thickness={51} speed={100} color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
							) }
						</div>
					</section>
				</main>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps)
{
	return {
	}
}

export const getServerSideProps = reduxWrapper.getServerSideProps(store => 
	async ({ req, res, query }) => 
	{
		if(query.account === undefined)
		{
			res.statusCode = 302;
			res.setHeader('Location', `/`);
		}
		else
		{
			return { 
				props: {
					account: query.account, 
				}
			}
		}
    }
);

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