import React from "react";
import Link from "next/link";
import { connect } from "react-redux";

class InnerMenu extends React.Component
{
	constructor(props)
	{
		super(props);
		this.state = {
			appeals: 0, 
		}

		this.menuRef = React.createRef();
	}

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

	componentDidMount()
	{
		let l = 0;
		let m = 0;
		const menu = [ "faq", "appeals" ];

		for(let i in menu)
		{
			if(this.props.router.asPath.indexOf(menu[i].link) > -1)
			{
				m = i;
			}
		}

		for(let i = 0; i < m; i++)
		{
			l = l + this.menuRef.current.children[i].getBoundingClientRect().width;
		}

		this.menuRef.current.scrollLeft = l - 50;
	}

	_handle_onToggleMenu = () => 
	{
		this.setState({
			menuOpened: !this.state.menuOpened,
		});
	};

	_getActiveLink = (route) => 
	{
		if (route.indexOf("/faq") > -1) return "FAQ";
		if (route.indexOf("/appeals") > -1) return "Мои обращения";
	
		return null;
	};

	_handle_onNewAppeal = () => 
	{
		this.props.router.push('/support/request/');
	}

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

		return (
			<aside className="flex">
				<button className="nav_toggle" onClick={ this._handle_onToggleMenu }>
					{ this.props.router && this._getActiveLink(this.props.router.asPath) }
				</button>
				<ul className={ menuOpened ? "aside_nav open" : "aside_nav" } ref={ this.menuRef }>
					<li>
						<Link href={`/support/faq`} shallow>
							<a className={ this.props.router && this.props.router.asPath.indexOf("faq") > -1 ? "active" : "" }>FAQ</a></Link>
					</li> 
					<li>
						<Link href={`/support/appeals`} shallow>
							<a className={ this.props.router && this.props.router.asPath.indexOf("appeals") > -1 ? "active" : "" }>Мои обращения { appeals > 0 && (<span>{ appeals }</span> ) }</a>
						</Link>
					</li>
				</ul>
				<button className="button button-blue new-appeal" onClick={ this._handle_onNewAppeal }>Новое обращение</button>
			</aside>
		)
	}
}

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

export default connect(mapStateToProps)(InnerMenu);