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 moment from "moment";
import { SpinnerCircular } from "spinners-react";

import { reduxWrapper } from "../store";

import Header from "./components/Header";
import Footer from "./components/Footer";
import Company from "./components/Company";
import Manager from "./components/Manager";
import InnerMenu from "./components/Events/InnerMenu";

import NotificationMessage from "./components/Events/NotificationMessage";

import { getEvents, getFilteredEvents } from "../actions";
import AccountLayout from "./components/Layout/Account";

class EventsPage extends React.Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
			events: [], 
			events_loaded: false, 
			filtered: undefined, 
			type: undefined, 
			types: {
				"osago_prolong": "additional", 
				"kasko_prolong": "additional", 
				"fingap_prolong": "additional", 
				"graph_change": "finance", 
				"end_contract": "finance", 
				"fine_gibdd": "fines", 
				"return_pts": "pts", 
			}, 
			loading: false, 
			search: "", 
			searched: false, 
		};
	}

	static getDerivedStateFromProps(nextProps, prevState)
	{
		return {
			events: nextProps.events, 
			events_loaded: nextProps.events_loaded, 
			filtered: nextProps.filtered, 
		};
	}

	componentDidMount()
	{
		const { events_loaded } = this.state;
		const { dispatch, router } = this.props;

		const hash = router.asPath.split('#')[1];
		console.log("HASH", hash);

		this.setState({ type: hash }, () => 
		{
			if(!events_loaded)
			{
				getEvents({ dispatch })
				.then(() => 
				{
					this._filterEvents();
				});
			}
		});
	}

	componentDidUpdate(prevProps, prevState)
	{
		const hash = this.props.router.asPath.split('#')[1];
		if(this.state.type !== hash)
		{
			this.setState({ type: hash });
		}
	}

	_handle_onChange_search = (value) => 
	{
		this.setState({ search: value });
	}

	_handle_onSearch = () => 
	{
		this.setState({ searched: true }, () => 
		{
			this._filterEvents();
		});
	}

	_handle_onSearchReset = () => 
	{
		this.setState({ searched: false, search: "" }, () => 
		{
			this._filterEvents();
		});
	}

	_filterEvents = () => 
	{
		console.log("_filterEvents");
		const { dispatch } = this.props;
		const { search } = this.state;

		getFilteredEvents({ dispatch, search });
	}

	_renderEvents = (events) => 
	{
		const { type, types } = this.state;
		const notifications = [];

		for(let i in events)
		{
			let event = events[i];

			if(type !== undefined && type !== types[ event.event_type ]) {}
			else
			{
				notifications.push(<NotificationMessage event={ event } key={ i } { ...this.props }/>);
			}
		}

		if(notifications.length > 0)
		{
			return (
				<ul className="list events-list">
					{ notifications }
				</ul>
			)
		}
		else
		{
			return (<p>Нет событий по выбранным условиям.</p>)
		}
	}

	render() 
	{
		const { loading, type, types, search, events, events_loaded, filtered, searched } = this.state;
		console.log("events", "type", type);

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta name="description" content="ЛК Эволюция автолизинга" />
				</Head>
				<Header {...this.props} />
				<AccountLayout>
					<div className="title_wrapper">
						<div className="left" style={{ flexDirection: "column" }}>
							<h1 className="section_title">События</h1>
						</div>
						<Company { ...this.props }/>
					</div>
					<div className="aside_container about">
						<InnerMenu { ...this.props } type={ type } types={ types } events={ filtered !== undefined ? filtered : events }/>
						<article>
							<div className="contract_search">
								<form onSubmit={ (event) => { event.preventDefault(); } }>
									<div className="form_field full">
										<input type="search" value={ search } placeholder="Поиск" onChange={ (event) => {
											this._handle_onChange_search(event.target.value);
										} }/>
									</div>
									<div className="search_form_buttons_wrapper">
										<button className="button search_button" disabled={ search !== "" ? false : true } onClick={ this._handle_onSearch }>Поиск</button>
										{ searched && (
											<button className="button" onClick={ this._handle_onSearchReset }>Сбросить</button>
										) }
									</div>
								</form>
							</div>
							{ events_loaded && (
								<>
									{ filtered !== undefined ? this._renderEvents(filtered) : this._renderEvents(events) }
								</>
							) }
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		events: state.events.list, 
		events_loaded: state.events.loaded, 
		filtered: state.events.filtered, 
	};
}

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

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