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 numeral from "numeral";
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 InnerMenu from "./components/InnerMenu";

import {
  getContractInfo,
  getContractHelpCard,
  getContractInsurance,
  getContractRegistration,
  getContractTelematic,
} from "./../../actions";
import ContractHeader from "./components/ContractHeader";

class ContractServicesPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      opened: [],
      date: null,
      car: null,
      contract_date: null,
      loading: false,
      helpcard: null,
      insurance: null,
      registration: null,
      telematic: null,
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    return {
      date: nextProps.date,
      car: nextProps.car,
      contract_date: nextProps.contract_date,
      helpcard: nextProps.helpcard,
      insurance: nextProps.insurance,
      registration: nextProps.registration,
      telematic: nextProps.telematic,
    };
  }

  componentDidMount() {
    if (!this.state.loading && this.props.number !== undefined) {
      this.setState({ loading: true }, () => {
        getContractInfo({
          dispatch: this.props.dispatch,
          number: this.props.number,
        });
        Promise.all([
          new Promise((resolve) => {
            getContractHelpCard({
              dispatch: this.props.dispatch,
              number: this.props.number,
            }).then(resolve());
          }),
          new Promise((resolve) => {
            getContractInsurance({
              dispatch: this.props.dispatch,
              number: this.props.number,
            }).then(resolve());
          }),
          new Promise((resolve) => {
            getContractRegistration({
              dispatch: this.props.dispatch,
              number: this.props.number,
            }).then(resolve());
          }),
          new Promise((resolve) => {
            getContractTelematic({
              dispatch: this.props.dispatch,
              number: this.props.number,
            }).then(resolve());
          }),
        ]).then(() => {
          this.setState({ loading: false });
        });
      });
    }
  }

  _handle_onCard = (card) => {
    const opened = [...this.state.opened];
    if (opened.indexOf(card) === -1) {
      opened.push(card);
    } else {
      opened.splice(opened.indexOf(card), 1);
    }

    this.setState({ opened: opened });
  };

	render() 
	{
		const { number } = this.props;
		const {
			opened,
			loading,
			date,
			car,
			contract_date,
			helpcard,
			insurance,
			registration,
			telematic,
		} = this.state;

		return (
			<React.Fragment>
				<Head>
					<title>ЛК Эволюция автолизинга</title>
					<meta name="description" content="ЛК Эволюция автолизинга" />
				</Head>
				<Header {...this.props} />
				<main>
					<section>
						<div className="clear"></div>
						<div className="container">
							<div className="title_wrapper">
								<div className="left" style={{ flexDirection: "column" }}>
									<ContractHeader number={ number } date={ date } car={ car }/>
								</div>
								<Company { ...this.props }/>
							</div>
							<div className="aside_container about">
								<InnerMenu number={number} {...this.props} />
								<article>
									{ 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="dropdown_blocks_list zero-margin gibdd">
											<div className={`dropdown_block open`}>
												<div className="block_body full">
													<div className="company">
														<p className="title lower">Штрафы ГИБДД</p>
														<ul>
															<li>Номер постановления: <b>3432434242334</b></li>
															<li>Страховая: <b>3 400 000,00 ₽</b></li>
															<li>Статус: <b>Оплачен</b></li>
															<li>Дата: <b>01/01/2020 </b></li>
															<li>Штраф:{" "}<b>п. 1.15 - Несоблюдение правил парковки </b></li>
															<li>
																<div className="dosc_list medium-icon">
																	<div className="row">
																		<p className="doc_name i-pdf extension">
																		№ 01/20/2020 (.PDF)
																		<span style={{"width":"100%"}}>Постановление</span>
																		</p>
																	</div>
																	<div className="row">
																		<p className="doc_name i-pdf extension">
																		Договор
																		<span style={{"width":"100%"}}>2021_3866 от 25.06.2021</span>
																		</p>
																	</div>
																</div>
															</li>
														</ul>
													</div>
												</div>
											</div>
										</div>
									) }
								</article>
							</div>
						</div>
					</section>
				</main>
				<Footer authenticated={ true }/>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		contract_date: state.contract.date,
		date: state.contract.date,
		car: state.contract.car,
		helpcard: state.contract.helpcard,
		insurance: state.contract.insurance,
		registration: state.contract.registration,
		telematic: state.contract.telematic,
	};
}

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

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