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 Select from 'react-select';
import NoSSR from "@mpth/react-no-ssr";


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 { inviteToEDO, sendPhoneChangeNumber, sendPhoneChangeNumberSmsCode, setUserPhone } from '../../actions';
import AccountLayout from "../components/Layout/Account";
import { getEDOOperatorList, getEDOInvitesList } from "../../actions";

class IndexPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false, 
			operator: undefined, 
			operators: null, 
			invites: null, 
			message: undefined, 
		};
	}

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

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

		getEDOOperatorList({ dispatch }).then(() => {}).catch(() => {});
		getEDOInvitesList({ dispatch }).then(() => {}).catch(() => {});
	}

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

		this.setState({ loading: true }, () => 
		{
			inviteToEDO()
			.then((message) => 
			{
				this.setState({ message })
			})
			.catch(() => 
			{
				this.setState({ message })
			});
		})
	}

	_handle_onOperatorChange = (operator) => 
	{
		this.setState({ operator });
	}

	render()
	{
		const { user, operators, invites, operator, loading, message } = this.state;

		var list = operators !== null && invites !== null ? [ ...operators, ...invites ] : null;

		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>
					<NoSSR>
						<div className="aside_container about">
							<InnerMenu { ...this.props } user={ user }/>
							<article className="questionnaire edo_detail">
								{/*}
								<p>Выберите своего оператора. Мы отправим вашей организации приглашение.</p>
								{*/}
								{ list !== undefined && list !== null ? (
									<>
										<p>Операторы ЭДО с которыми установлена связь</p>
										<p><br/></p>
										{ message === undefined ? (
											<form ref={ this.ref_form } onSubmit={ this._handle_onFormSubmit } onKeyDown={(e) => {if (e.key === 'Enter') e.preventDefault() }}>
												<div className="edo_operators_settings_list">
													{ list.length > 0 ? 
														<>
															{ operators.map((operator, index) => (
																<div key={ index } className="edo_operators_settings_list_item">{ operator.provider_edo }
																	<a href={ operator.url_edo } >{ operator.url_edo }</a>
																</div>
															)) }
															{ invites.map((invite, index) => (
																<div key={ index } className="edo_operators_settings_list_item invite">{ invite.provider_edo }
																	<a href={ invite.url_edo } >{ invite.url_edo }</a>
																</div>
															)) }
														</> : (
															<p>У Вас пока нет подключенных операторов ЭДО. Запросите отправку нового приглашения.</p>
														) 
													}
												</div>
												<div className="form_field" style={{ display: "flex", justifyContent: "flex-end" }}>
													<button type="submit" className="button button-blue" style={{ minWidth: "232px" }}>
														{ loading ? ( 
															<SpinnerCircular size={24} thickness={100} speed={100} color="rgba(255, 255, 255, 1)" secondaryColor="rgba(255, 255, 255, 0.5)" style={{ marginTop: "0px" }}/>
														) : "Отправить новое приглашение" }
													</button>
												</div>
											</form>
										) : (
											<p>{ message }</p>
										) }
									</>
								) : (
									<div style={{ minHeight: 200, display: "flex", justifyContent: "center", alignItems: "center", }}>
										<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
									</div>
								) }
							</article>
						</div>
					</NoSSR>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

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

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