import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	Dropdown as SemanticDropdown,
	Icon as SemanticIcon,
	Image as SemanticImage,
	Input as SemanticInput,
	Menu as SemanticMenu,
} from 'semantic-ui-react';
import Avatar from '../Avatar';

import Logo from './pinpoint.svg';

import * as styles from './Style.less';

export default class NavBar extends Component {
	static propTypes = {
		menu: PropTypes.array.isRequired,
		admin: PropTypes.array,
		logoUrl: PropTypes.string,
		avatarUrl: PropTypes.string,
		// notificationCount: PropTypes.number,
		// supportCount: PropTypes.number,
		onSignout: PropTypes.func,
		onClick: PropTypes.func.isRequired,
		onNotificationClick: PropTypes.func,
		onDocsClick: PropTypes.func,
		onSupportClick: PropTypes.func
	};

	static defaultProps = {
		admin: [],
		logoUrl: null,
		avatarUrl: '',
		// notificationCount: 0,
		// supportCount: 0,
		onSignout: null,
		onNotificationClick: null,
		onDocsClick: null,
		onSupportClick: null
	};

	constructor(props) {
		super(props);

		this.state = {
			menu: this.createMenu(props.menu),
			admin: props.admin.length ? props.admin : null,
			// notificationCount: props.notificationCount,
			// supportCount: props.supportCount,
			search: {
				value: ''
			}
		};

		this.AnimateSearchIcon = function animation(element){if(!window.requestAnimationFrame){let a=null;window.requestAnimationFrame=(t)=>{const e=(new Date()).getTime();a||(a=e);const s=Math.max(0,16-(e-a));const n=window.setTimeout(()=>{t(e+s);},s);return a=e+s,n;};}this.element=element;this.svg=(function find(e){let parent=e.parentNode;if(parent.tagName!=='svg'){parent=find(parent);}return parent;}(this.element));this.paths=this.element.querySelectorAll('.search-icon-group');this.time={start:null,total:200};this.status={display:[0,1],animating:false};this.doMaths=function f(progress,tweenOut,tweenIn,duration){return(progress /=duration / 2)<1?tweenIn / 2*progress*progress*progress*progress+tweenOut:-tweenIn / 2*((progress-=2)*progress*progress*progress-2)+tweenOut;};this.getSize=()=>{const viewBox=this.svg.getAttribute('viewBox');this.size=viewBox?{width:viewBox.split(' ')[2],height:viewBox.split(' ')[3]}:this.svg.getBoundingClientRect();};this.getProgress=(timer)=>{return this.time.start||(this.time.start=timer),timer-this.time.start;};this.checkProgress=(progress)=>{if(this.time.total>progress){window.requestAnimationFrame(this.triggerAnimation.bind(this));}else{const{display}=this.status;this.status={display:this.status.display.reverse(),animating:false};this.time.start=null;this.paths[display[0]].removeAttribute('aria-hidden');this.paths[display[1]].setAttribute('aria-hidden','true');}};this.triggerAnimation=(timer)=>{const progress=this.getProgress(timer);this.getSize();this.animateIcon(progress);this.checkProgress(progress);};this.animateIcon=(progress)=>{if(progress>this.time.total){progress=this.time.total;}if(progress<0){progress=0;}const{display}=this.status;this.paths[display[0]].style.display=progress>this.time.total / 2?'none':'block';this.paths[display[1]].style.display=progress>this.time.total / 2?'block':'none';this.scaleIcon(progress,display[0],display[1]);};this.scaleIcon=(progress,hide,show)=>{const shrink=this.doMaths(Math.min(progress,this.time.total / 2),1,-0.2,this.time.total / 2).toFixed(2);const grow=this.doMaths(Math.max(progress-this.time.total / 2,0),0.2,-0.2,this.time.total / 2).toFixed(2);this.paths[hide].setAttribute('transform',`translate(${this.size.width*(1-shrink)/ 2}${this.size.height*(1-shrink)/ 2})scale(${shrink})`);this.paths[show].setAttribute('transform',`translate(${this.size.width*grow / 2}${this.size.height*grow / 2})scale(${(1-grow)})`);};this.showSearch=(()=>{this.status.display=[1,0];this.status.animating||(this.status.animating=true,window.requestAnimationFrame(this.triggerAnimation.bind(this)));}).bind(this);this.showClear=(()=>{this.status.display=[0,1];this.status.animating||(this.status.animating=true,window.requestAnimationFrame(this.triggerAnimation.bind(this)));}).bind(this);}; // eslint-disable-line
	}

	componentDidMount() {
		if (global.test) {
			this.searchIcon = document.getElementById('search-icon');
			this.searchIcon.animateSearchIcon = new this.AnimateSearchIcon(this.searchIcon);
		}
	}

	componentWillReceiveProps(nextProps) {
		this.setState({
			menu: this.createMenu(nextProps.menu),
			admin: nextProps.admin.length ? nextProps.admin : null,
			// notificationCount: nextProps.notificationCount,
			// supportCount: nextProps.supportCount
		});
	}

	onSearchChange(value) {
		if (this.state.search.value.length === 0 && value.length === 1) {
			this.searchIcon.animateSearchIcon.showClear();
		} else if (this.state.search.value.length > 0 && value.length === 0) {
			this.searchIcon.animateSearchIcon.showSearch();
		}

		this.setState({
			search: {
				value
			}
		});
	}

	onSearchClear() {
		this.searchIcon.animateSearchIcon.showSearch();

		this.setState({
			search: {
				value: ''
			}
		});
	}

	createMenu(menu) {
		const element = [];

		menu.forEach((noun) => {
			element.push(
				<SemanticDropdown
					trigger={(
						<SemanticMenu.Item
							name={noun.title}
							active={noun.active || false}
						>
							<SemanticIcon className={noun.icon} />
							{noun.title}
						</SemanticMenu.Item>
					)}
					icon={null}
					key={noun.title}
				>
					<SemanticDropdown.Menu
						className={styles.SubMenu}
					>
						{
							noun.menu.map(section => (
								<React.Fragment
									key={section.title}
								>
									<SemanticDropdown.Header>
										{section.title}
									</SemanticDropdown.Header>
									{
										section.menu.map(route => (
											<SemanticDropdown.Item
												key={route.title}
												text={route.title}
												value={route.key}
												description={route.description || null}
												active={route.active || false}
												onClick={this.props.onClick}
											/>
										))
									}
								</React.Fragment>
							))
						}
					</SemanticDropdown.Menu>
				</SemanticDropdown>
			);
		});

		return element;
	}

	render() {
		return (
			<SemanticMenu
				className={styles.Menu}
				inverted
				borderless
			>
				<SemanticMenu.Item
					className={styles.Logo}
				>
					{
						this.props.logoUrl ? (
							<a href="/">
								<SemanticImage
									src={Logo}
								/>
							</a>
						) : (
							<SemanticImage
								src={Logo}
							/>
						)
					}
				</SemanticMenu.Item>
				{this.state.menu.map(menu => menu)}
				{
					(this.props.avatarUrl || this.props.onSignout) && (
						<SemanticMenu.Menu
							position="right"
						>
							{
								global.test && (
									<SemanticInput
										className={styles.Search}
										placeholder="Search"
										labelPosition="right"
										onChange={(e, { value }) => this.onSearchChange(value)}
										value={this.state.search.value}
									>
										<span className={styles.SearchSpacer}>{this.state.search.value}</span>
										<input />
										<svg
											xmlns="http://www.w3.org/2000/svg"
											viewBox="0 0 512 512"
											height="512"
											width="512"
											onClick={() => this.onSearchClear()}
										>
											<g id="search-icon">
												<g className="search-icon-group">
													<path fill="currentColor" d="M461.5,410l-82.3-82.3c-3.7-3.7-8.7-5.8-14-5.8h-13.4c22.8-29.1,36.3-65.8,36.3-105.6c0-94.8-76.8-171.6-171.6-171.6 S44.8,121.6,44.8,216.4S121.6,388,216.4,388c39.9,0,76.5-13.5,105.6-36.3v13.4c0,5.3,2.1,10.3,5.8,14l82.3,82.3 c7.8,7.8,20.3,7.8,28,0l23.4-23.4C469.1,430.3,469.1,417.8,461.5,410z M216.4,322c-58.3,0-105.6-47.2-105.6-105.6 c0-58.3,47.2-105.6,105.6-105.6c58.3,0,105.6,47.2,105.6,105.6C322,274.7,274.8,322,216.4,322z" />
												</g>
												<g className="search-icon-group" aria-hidden="true" style={{ display: 'none' }}>
													<path fill="currentColor" d="M303.6,256l107.7-107.7c6.2-6.2,6.2-16.3,0-22.6l-25-25c-6.2-6.2-16.3-6.2-22.6,0L256,208.4L148.3,100.7 c-6.2-6.2-16.3-6.2-22.6,0l-25,25c-6.2,6.2-6.2,16.3,0,22.6L208.4,256L100.7,363.7c-6.2,6.2-6.2,16.3,0,22.6l25,25 c6.2,6.2,16.3,6.2,22.6,0L256,303.6l107.7,107.7c6.2,6.2,16.3,6.2,22.6,0l25-25c6.2-6.2,6.2-16.3,0-22.6L303.6,256z" />
												</g>
											</g>
										</svg>
									</SemanticInput>
								)
							}
							<SemanticDropdown
								trigger={(
									<SemanticMenu.Item
										className={styles.Avatar}
									>
										{
											typeof this.props.avatarUrl !== 'undefined' && (
												<Avatar
													src={this.props.avatarUrl}
												/>
											)
										}
										<SemanticIcon name="ellipsis vertical" />
									</SemanticMenu.Item>
								)}
								icon={null}
								direction="left"
							>
								<SemanticDropdown.Menu
									className={styles.SubMenu}
								>
									{
										this.props.onNotificationClick && (
											<SemanticDropdown.Item
												onClick={this.props.onNotificationClick}
											>
												<SemanticIcon className="envelope" />
												<span className="text">Notifications</span>
											</SemanticDropdown.Item>
										)
									}
									<SemanticDropdown.Item
										onClick={this.props.onSupportClick}
									>
										<SemanticIcon className="headset" />
										<span className="text">Support</span>
									</SemanticDropdown.Item>
									<SemanticDropdown.Item
										onClick={this.props.onDocsClick}
									>
										<SemanticIcon className="info" />
										<span className="text">Glossary</span>
									</SemanticDropdown.Item>
									<SemanticDropdown.Item
										onClick={this.props.onSignout}
									>
										<SemanticIcon className="sign out" />
										<span className="text">Sign Out</span>
									</SemanticDropdown.Item>
									{
										(this.state.admin && this.state.admin.length > 0) && (
											<>
												<SemanticDropdown.Header>
													Organization Settings
												</SemanticDropdown.Header>
												{
													this.state.admin.map(route => (
														<SemanticDropdown.Item
															key={route.key}
															text={route.title}
															value={route.key}
															active={route.active || false}
															onClick={this.props.onClick}
														/>
													))
												}
											</>
										)
									}
								</SemanticDropdown.Menu>
							</SemanticDropdown>
						</SemanticMenu.Menu>
					)
				}
			</SemanticMenu>
		);
	}
}
