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

import {
	getContractInfo,
	getContractAgreement,
	getContractRules,
	getFile,
	setAppealsRead,
} from "../../actions";
import AccountLayout from "../components/Layout/Account";
import RequestFile from "./components/RequestFile";

class SupportAppealsPage extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			active: true, 
			appeals: null,
			loading: false,
		};
	}

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

	componentDidMount()
	{
		setTimeout(() => 
		{
			const appeals = [];
			if(this.state.appeals !== undefined && this.state.appeals !== null && this.state.appeals.list !== undefined && this.state.appeals.list !== null)
			{
				for(let i in this.state.appeals.list)
				{
					if(this.state.appeals.list[i].read !== true)
					{
						appeals.push({ number: this.state.appeals.list[i].number, status: this.state.appeals.list[i].status });
					}
				}
			}

			console.log("appeals");
			console.log(appeals);

			setAppealsRead({ dispatch: this.props.dispatch, appeals });
		}, 1000);
	}

	componentWillUnmount()
	{
	}

	_activeAppealsCount = () => 
	{
		const { appeals } = this.state;
		let count = 0;

		if(appeals.list !== undefined && appeals.list !== null)
		{
			for(let i in appeals.list) { if(appeals.list[i].status === "active") { count++; } }
		}

		return count;
	}

	_handle_onActive = () => 
	{
		this.setState({ active: this.state.active ? false : true });
	}

	render()
	{
		const { number } = this.props;
		const { loading, active, appeals } = this.state;

		const status = {
			active: { title: "Активное", color: "#04A8A4" }, 
			closed: { title: "Закрыто", color: "#000", }, 
			cancelled: { title: "Отменено", color: "#A8026B", }
		};

		const active_count = this._activeAppealsCount();
		console.log(appeals);

		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 } />
						<article>
							<div style={{ height: "30px", display: "flex", flexDirection: "row", alignItems: "flex-start", justifyContent: "flex-end", }}>
								<div className="form_field">
									<input type="checkbox" hidden id="only_active" name="only_active" checked={ active ? true : false } onChange={ this._handle_onActive }/>
									<label htmlFor="only_active">Показывать только активные обращения</label>
								</div>
							</div>
							<div className="appeal_list">
								{ appeals !== undefined && appeals !== null && appeals.list !== undefined && appeals.list !== null && (
									<>
										{ appeals.list.length > 0 ? (
											<>
												{ active && active_count === 0 ? (
													<div style={{ justifyContent: "center", alignItems: "center", display: "flex", minHeight: "150px" }}>
														<p>У Вас нет активных обращений.<br/><a className="interactive" onClick={ this._handle_onActive }>Показать все обращения</a></p>
													</div>
												) : (
													<>
														{ appeals.list.map((appeal, index) => 
														{
															if(active) { if(appeal.status !== "active") { return null; } }

															return (
																<div className="appeal_item" key={ index }>
																	<div className="item_header">
																		<p>Номер обращения: <b>{ appeal.number } от { moment(appeal.created_date, "YYYY-MM-DD").format("DD.MM.YYYY") }</b></p>
																		<p>Ваш персональный менеджер: <b>{ appeal.owner }</b></p>
																		{ appeal.contracts.length > 0 && (
																			<p>Договор{ appeal.contracts.length > 1 && "ы" }: <b>{ appeal.contracts.map((contract, contract_index) => (<span key={ contract_index }>№ { contract }{ contract_index < appeal.contracts.length - 1 && ", " }</span>)) }</b></p>																		
																		) }
																		<div className="status" style={{ backgroundColor: status[appeal.status].color }}>{ status[appeal.status].title }</div>
																	</div>
																	<div className="item_body">
																		<div className="item_text">
																			<p><b>Тема запроса</b></p>
																			<p>{ appeal.subject }</p>
																			{ appeal.client_request !== null && appeal.client_request !== "" && (
																				<>
																					<p><b>Текст запроса</b></p>
																					<p dangerouslySetInnerHTML={{ __html: appeal.client_request.replace("\\n", "<br/>") }}></p>
																				</>
																			) }
																			{ appeal.documents.length > 0 && (
																				<div className="dosc_list medium-icon">
																					{ appeal.documents.map((file, index) => {
																						if(file.doc_direction !== "incoming") { return null; }
																						return (<RequestFile key={ `template_${ index }` } file={ file }/>)
																					}) }
																				</div>
																			) }
																		</div>
																		<div className="item_text">
																			<p><b>Ответ службы клиентского сервиса</b></p>
																			<p dangerouslySetInnerHTML={{ __html: appeal.answer === null || appeal.answer === "" ? "Без ответа" : appeal.answer.replace("\\n", "<br/>") }}></p>
																			{ appeal.documents.length > 0 && (
																				<div className="dosc_list medium-icon">
																					{ appeal.documents.map((file, index) => {
																						if(file.doc_direction !== "outgoing") { return null; }
																						return (<RequestFile key={ `template_${ index }` } file={ file }/>)
																					}) }
																				</div>
																			) }
																		</div>
																	</div>
																</div>
															)
														}) }
													</>
												) }
											</>
										) : (
											<div style={{ justifyContent: "center", alignItems: "center", display: "flex", minHeight: "150px" }}>
												<p>У Вас пока нет обращений.</p>
											</div>
										) }
									</>
								)}
							{/*}
								<div className="appeal_item">
									<div className="item_header">
										<p>Номер обращения: <b>123 от 13.04.2022</b></p>
										<p>Отвественный ОРК: <b>Иванов И.И.</b></p>
										<p>Договор: <b>№2021_1655, №2021_1655</b></p>
										<div className="status">Активное</div>
									</div>
									<div className="item_body">
										<div className="item_text">
											<p><b>Тема запроса</b></p>
											<p>Текстовый контент</p>
										</div>
										<div className="item_text">
											<p><b>Текст ответа ОРК</b></p>
											<p>Текстовый контент</p>
										</div>
									</div>
								</div>
								<div className="appeal_item">
									<div className="item_header">
										<p>Номер обращения: <b>123 от 13.04.2022</b></p>
										<p>Отвественный ОРК: <b>Иванов И.И.</b></p>
										<p>Договор: <b>№2021_1655, №2021_1655</b></p>
									</div>
									<div className="item_body">
										<div className="item_text">
											<p><b>Тема запроса</b></p>
											<p>Текстовый контент</p>
										</div>
										<div className="item_text">
											<p><b>Текст ответа ОРК</b></p>
											<p>Текстовый контент</p>
											<div className="dosc_list medium-icon">
												<div className="row">
													<p className="doc_name i-pdf extension">
														№2021_1655 от 20.04.2021
														<span>2021_1655 от 20.04.2021</span>
													</p>
												</div>
												<div className="row">
													<p className="doc_name i-pdf extension">
														№2021_1655 от 20.04.2021
														<span>2021_1655 от 20.04.2021</span>
													</p>
												</div>
											</div>
										</div>
									</div>
								</div>
							{*/}
							</div>
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		);
	}
}

function mapStateToProps(state, ownProps) 
{
	return {
		appeals: state.support.appeals, 
	};
}

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

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