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 AccountLayout from "../components/Layout/Account";
import TemplateFile from "./components/TemplateFile";

import {
	getSupportThemes,
	resetFilteredThemes,
} from "../../actions";

class SupportPage extends React.Component 
{
	constructor(props) 
	{
		super(props);
		this.state = {
			themes: null, 
			question_selected: undefined, 
			appeals: null, 
			appeal: null, 
			filtered: null, 
			loading: false, 
			search: "", 
			query: "", 
			searched: false, 
		};

		this.question_refs = [];
	}

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

	componentDidMount() 
	{
		if (!this.state.loading) 
		{
			this.setState({ loading: true }, () => 
			{
				getSupportThemes({ dispatch: this.props.dispatch })
				.then(() => 
				{
					let question_selected = undefined;
					let found = false;

					for(let t in this.state.themes)
					{
						for(let q in this.state.themes[t].questions)
						{
							this.question_refs[this.state.themes[t].questions[q].id] = React.createRef();

							if(this.props.router.asPath.indexOf(this.state.themes[t].questions[q].id) > -1)
							{
								question_selected = this.state.themes[t].questions[q].id;
								found = true;
							}
						}
					}

					this.setState({ loading: false, question_selected: question_selected }, () => 
					{
						if(question_selected !== undefined)
						{
							setTimeout(() => {
								this.question_refs[question_selected].current.scrollIntoView({
									behavior: 'smooth',
									block: 'center',
								});
							}, 100);
						}
					});
				})
				.catch(() => {});
			});
		}
	}

	componentWillUnmount()
	{
	}

	_handle_onQuestion = (question) => 
	{
		if(this.state.question_selected === question)
		{
			this.setState({ question_selected: undefined });
		}
		else
		{
			this.setState({ question_selected: question });
		}
	}

	_handle_onRequest = (question) => 
	{
		this.props.router.push(`/support/request#${ question }`);
	}

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

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

		this.setState({ searched: true, query: search }, () => 
		{
			getSupportThemes({ dispatch: this.props.dispatch, query: search })
			.then(() => 
			{
			});
		});
	}

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

	_handle_onLocalLink = (id) => 
	{
		const { dispatch } = this.props;

		window.location = `/support/faq#${ id }`;
		this.setState({ searched: false, search: "", query: "", question_selected: id }, () => 
		{
			resetFilteredThemes({ dispatch });
			setTimeout(() => {
				this.question_refs[id].current.scrollIntoView({
					behavior: 'smooth',
					block: 'center',
				});
			}, 100);
		});
	}

	_getMarks = (content) => 
	{
		const { query } = this.state;
		const search_array = query.split(" ");

		const chunks = [];
		const content_array = content.split(" ");

		for(let i in content_array)
		{
			let found = false;
			for(let s in search_array)
			{ 
				if(content_array[i].toLowerCase() == search_array[s].toLowerCase())
				{
					found = true; 
				}
			}

			if(found)
			{
				chunks.push(`<mark>${ content_array[i] }</mark>`);
			}
			else
			{
				chunks.push(content_array[i]);
			}
		}

		return chunks.join(" ");
	}

	render() 
	{
		//filtered,
		const { loading, themes, filtered, question_selected, searched, appleals, search } = this.state;

		let filtered_count = 0;
		if(filtered !== undefined && filtered !== null)
		{
			for(let i in filtered)
			{
				filtered_count = filtered_count + filtered[i].questions.length;
			}
		}

		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>
							{ loading ? (
								<div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "center", }}>
									<SpinnerCircular size={ 90 } thickness={ 51 } speed={ 100 } color="rgba(28, 1, 169, 1)" secondaryColor="rgba(236, 239, 244, 1)" />
								</div>									
							) : (
								<>
									<div className="contract_search">
										<form onSubmit={(event) => { event.preventDefault(); }}>
											<div className="form_field full">
												<input type="search" value={ search } placeholder="Поиск" onChange={(event) => { this._handle_onChangeSearchQuery(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>
									{/* Результат поиска */}
									{ searched && filtered !== undefined && filtered !== null ? (
										<>
											{ filtered_count > 0 ? (
												<>
													{ filtered.map((theme, theme_index) => (
														<React.Fragment key={ theme_index }>
															{ theme.questions.map((question, index) => 
															(
																<div className="search_list" key={ `searched_${ question.id }` }>
																	<div className="search_item">
																		<p className="item_title" dangerouslySetInnerHTML={{ __html: `${ theme._name } / ${ question._title }` }}></p>
																		<p dangerouslySetInnerHTML={{ __html: question._answer }}/>
																		{/*}
																		<p>К каждой теме свободное <mark>html поле для миниинструкции</mark> (со ссылками на формы документов и документы). Привязка к теме обращения в CRM</p>
																		{*/}
																		<div style={{ display: "flex", flexDirection: "row", alignItems: "flex-end", justifyContent: "flex-end" }}>
																			<a className="interactive" onClick={ () => { this._handle_onLocalLink(question.id) } }>Подробнее</a>
																		</div>
																	</div>
																</div>
															)) }
														</React.Fragment>
													)) }
												</>
											) : (
												<p>К сожалению по Вашему запросу нет результатов.</p>
											) }
										</>
									) : (
										<div className="list faq-list">
											{ themes !== undefined && themes !== null && themes.map((theme) => 
											(
												<div className="faq_item" key={ `theme_${ theme.id }` }>
													<p className="item_title">{ theme.name }</p>
													<div className="dropdown_blocks_list">
														{ theme.questions.map((question) => 
														(
															<div ref={ this.question_refs[question.id] } className={ `dropdown_block ${ question.id === question_selected && "open" }` } key={ `question_${ question.id }` }>
																<div className={ `block_header` } onClick={ () => this._handle_onQuestion(question.id) }>
																	<p>{ question.title }</p>
																	<button></button>
																</div>
																<div className="block_body" style={{ paddingBottom: "20px" }}>
																	<div className="column full">
																		<div className="column_text_block">
																			<p><b>Процедура</b></p>
																			<p dangerouslySetInnerHTML={{ __html: question.answer }}/>
																		</div>
																		{ question.documents !== null && (
																			<div className="column_text_block">
																				<p><b>Документы</b></p>
																				<p dangerouslySetInnerHTML={{ __html: question.documents }}/>
																			</div>
																		) }
																		{ question.templates !== null && (
																			<div className="column_text_block">
																				<p><b>Шаблоны документов</b></p>
																				<div className="dosc_list medium-icon">
																					{ question.templates.map((template, index) => (<TemplateFile key={ `template_${ index }` } template={ template } />)) }
																				</div>
																			</div>
																		) }
																		{ question.request && (
																			<button className="button button-blue" onClick={ () => this._handle_onRequest(question.id) }>Создать обращение</button>
																		) }
																	</div>
																</div>
															</div>
														)) }
													</div>
												</div>
											)) }
										</div>
									) }
								</>
							) }
						</article>
					</div>
				</AccountLayout>
				<Footer/>
			</React.Fragment>
		);
	}
}

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

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

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