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

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 DateInput from "../components/DatePicker";
import DownloadPrintFormPdfButton from "../components/DownloadPrintFormPdfButton";
import DownloadFinesPdfButton from "../components/DownloadFinesPdfButton";

import {
  getContractInfo, 
  getContractFines, 
} from "../../actions";
import AccountLayout from "../components/Layout/Account";
import ContractHeader from "./components/ContractHeader";

const TYPES = {
  upd: "УПД по очередным платежам",
  upd_avans: "УПД по авансовым платежам",
  billfines: "Счета-уведомления на пени",
  billgibdd: "BillGIBDD",
  fines: "Штрафы ГИБДД",
};

class ContractFinesPage extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			loading: false, 
			contracts_info: [], 
			fines: null, 
			all: false, 
		};
	}

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

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

		if(!this.state.loading && number !== undefined) 
		{
			this.setState({ loading: true }, () => 
			{
				if(this.state.contracts_info[ number ] === undefined)
				{
					getContractInfo({ dispatch, number });
				}
	
				getContractFines({ dispatch, number }).then(() => 
				{
					this.setState({ loading: false });
				})
				.catch(() => {});
			});
		}
	}

	componentDidUpdate(prevProps, prevState) 
	{
	}

	_handle_onShowMore = () => 
	{
		this.setState({ all: true });
	}

	_renderFines = (fines) => 
	{
		console.log("_renderFines", "fines", fines);

		const { number } = this.props;
		const { all } = this.state;

		const status = {
			NotPaid: "danger",
			PaidEvolution: "success",
			PaidIndependently: "success",
		};

		if (fines.length > 0) 
		{
			return (
				<>
						<div className="dropdown_blocks_list">
							{ fines.slice(0, all ? fines.length : 3).map((fine, fine_index) => (
								<div className="dropdown_block open" key={fine_index}>
									<div className="block_body">
										<div className="fines_detail">
											<p>
												№ постановления: <b>{fine.fine_number}</b>
											</p>
											<ul>
												<li>
													Дата нарушения:{" "}
													<b>
														{moment(fine.violation_date).format("DD.MM.YYYY")}
													</b>
												</li>
												
												<li>
													Сумма:{" "}
													<b style={{ whiteSpace: "nowrap" }}>
														{numeral(fine.amount).format(" ., ")}&nbsp;₽
													</b>
												</li>
												
												<li>
													Статус:{" "}
													<b className={status[fine.status_code]}>
														{fine.status}
													</b>
												</li>
											</ul>

											<ul>
												{ fine.violation_place !== undefined && fine.violation_place !== null && (
													<li>
														Место нарушения: <b>{fine.violation_place}</b>
													</li>
												) }
												{fine.gibdd !== undefined && fine.gibdd !== null && (
													<li>
														Подразделение: <b>{fine.gibdd}</b>
													</li>
												)}
											</ul>
											<p className="fines_doc">
												Штраф: {fine.fine_title}
											</p>
										</div>
										{ fine.status_code !== "PaidIndependently" && (
											<div className="dosc_list medium-icon">
												<div className="row">
													<p
														className="doc_name i-pdf i-medium"
														style={{ marginBottom: "0px" }}
													>
														Счет на оплату
													</p>
													<DownloadFinesPdfButton
														className="download-icon"
														filename={`evolution_fine_${fine.fine_number}.pdf`}
														before={
															fine.status_code === "NotPaid" ? true : false
														}
														contract={number}
														num={fine.fine_number}
													/>
												</div>
											</div>
										) }
									</div>
									{/*}
										<DownloadPrintFormPdfButton className="download-icon" filename={ `${ number }_${ upd_document.type }_${ upd_document.num }.pdf` } contract={ number } num={ upd_document.num } date={ upd_document.date } type={ upd_document.type }/>
									{*/}
								</div>
							)) }
							{ !all && fines.length > 3 && (
								<div
									className="row"
									style={{
										display: "flex",
										justifyContent: "center",
										corsor: "pointer",
									}}
									onClick={ this._handle_onShowMore } 
								>
									<p style={{ paddingTop: "15px", color: "#747474" }}>
										Еще {fines.length - 3}{" "}
										{pluralize(
											fines.length - 3,
											"постановлений",
											"постановление",
											"постановления",
											"постановлений"
										)}
									</p>
								</div>
							) }
						</div>
				</>
			);
		}

		return (
			<>
				<div className="block-column">
					<div style={{ display: "flex", alignItems: "center" }}>
						<p>Штрафов не найдено.</p>
						<p>&nbsp;</p>
					</div>
				</div>
			</>
		);
	}

	render() 
	{
		const { number } = this.props;
		const { loading, contracts_info, fines, } = this.state;

		let { date, car, status } = contracts_info[ number ] !== undefined ? contracts_info[ number ] : {};

		console.log("fines");
		console.log(fines);

		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" }}>
							<ContractHeader number={ number } date={ date } car={ car }/>
						</div>
						<Company { ...this.props }/>
					</div>
					<div className="aside_container about">
						<InnerMenu number={ number } status={ status } { ...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>
												{fines !== undefined && fines !== null ? (
													<>
														{this._renderFines(fines)}
													</>
												) : null}
											</div>
										</div>
									</div>
								</div>
							) }
								{/*}
								<>
									<div className="dropdown_blocks_list">
									</div>
								</>
								{*/}
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		)
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		contracts_info: state.contracts_info, 
		contract_date: state.contract.date, 
		date: state.contract.date, 
		car: state.contract.car, 
		fines: state.contract.fines, 
	};
}

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

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

{
/*}
	<div className="block_body">
		<div className="transaction_detail">
			<p>№ постановления: <b>3432434242334</b></p>
			<ul>
				<li>Сумма: <b>3 000,00 р.</b></li>
				<li>Дата:  <b>01/01/2020</b></li>
				<li>Статус: <b className="success">Оплачен</b></li>
				<li>Штраф: п. 1.15 - Несоблюдение правил парковки </li>
			</ul>
		</div>
	</div>
{*/
}
