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

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

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

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

class FinalsPage extends React.Component 
{
	
	constructor(props)
	{
		super(props);
		this.state = {
			loading: false, 
			contracts: null, 
			search: "", 
		}
	}

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

	componentDidMount()
	{
		this.setState({ loading: true }, () => 
		{
			getContractsList({ dispatch: this.props.dispatch, all: true }).then(() => {
				this.setState({ loading: false });
			}).catch(() => {});
		});
	}

	_handle_onChange_search = (value) => 
	{
		if(this.state.value !== "" && value === "")
		{
			this.setState({ search: value }, () => {
				this._handle_onSearch();
			});
		}
		else
		{
			this.setState({ search: value });
		}
	}

	_handle_onSearch = () => 
	{
		const { search, } = this.state;

		this.setState({ loading: true, }, () => 
		{
			getContractsList({ dispatch: this.props.dispatch, search, all: true}).then(() => {
				this.setState({ loading: false });
			}).catch(() => {});
		});
	}

	render()
	{
		const { loading, search, contracts, } = 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 }/>
						<article>
							<div className="contract_search">
								<form onSubmit={ (event) => { event.preventDefault(); } }>
									<div className="form_field single">
										<input type="search" value={ search } placeholder="Поиск по номеру договора, марке и модели транспорта, VIN и госномеру ТС" onChange={ (event) => {
											this._handle_onChange_search(event.target.value);
										} }/>
									</div>
									<button className="button" disabled={ search !== "" ? false : true } onClick={ this._handle_onSearch }>Поиск</button>
								</form>
							</div>
							{ loading ? (
								<div className="table_row table_header" style={{ minHeight: 300, 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>
							) : (
								<div className="dosc_list" style={ contracts !== undefined && contracts !== null && contracts.length > 0 ? {} : { display: "flex", justifyContent: "center" }}>
									{ contracts !== undefined && contracts !== null && (
										<>
											{ contracts.length > 0 ? contracts.map((contract, index) => (
												<div className="row" key={ index }>
													<p className="doc_name i-doc full">
														<Link href={ `/contract/${ contract.number }/documents` }><a>Договор { contract.number } от { moment(contract.date).format("DD.MM.YYYY") }</a></Link>
														<span>{ contract.car.brand.name } { contract.car.model.name } | { contract.car.reg_number !== undefined && contract.car.reg_number !== null ? contract.car.reg_number : "без рег. номера" } | { contract.car.vin_number }</span>
													</p>
												</div>
											)) : (
												<p>Нет договоров для отображения</p>
											) }
										</> 
									) }
								</div>
							) }
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps)
{
	return {
		contracts: state.contracts.list, 
	}
}

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

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