import * as React from 'react';
import { Colors } from '../../models/colors';
import { Query } from '../../models/query';
import { iconStyles, tooltipWrapper } from './tooltip.style';

export interface TooltipProps {
	icon?: JSX.Element;
	id?: string;
	event?: string;
	eventOff?: string;
	globalEventOff?: string;
	palette?: Colors;
	query?: Query;
}

type TooltipContainerProps = TooltipProps & {
	render: (close: (e: React.MouseEvent<HTMLElement>) => void) => JSX.Element;
};

interface TooltipState {
	show: boolean;
}

class Tooltip extends React.PureComponent<TooltipContainerProps, TooltipState> {
	constructor(props: TooltipContainerProps) {
		super(props);
		this.state = {
			show: false
		};
	}

	unclicker = (e: React.MouseEvent<HTMLElement>) => {
		e.nativeEvent.stopImmediatePropagation();
	};

	open = () => {
		this.setState({
			show: true
		});
		document.addEventListener('click', this.close);
	};

	close = () => {
		this.setState({
			show: false
		});
		document.removeEventListener('click', this.close);
	};

	onClick = () => {
		this.state.show === false ? this.open() : this.close();
	};

	onKeyDown = (e: React.KeyboardEvent<HTMLAnchorElement>) => {
		switch (e.keyCode) {
			case 13: // enter
				this.state.show === false ? this.open() : this.close();
				break;
			case 27: // escape
				if (this.state.show) this.close();
		}
	};

	render() {
		const event = this.props.event || 'click';

		return (
			<React.Fragment>
				<span className={iconStyles()}>
					<a
						data-tip
						data-for={this.props.id}
						onClick={this.onClick}
						data-place="top"
						data-event={event}
						data-gtm={`tooltip-${this.props.id}`}
						onKeyDown={this.onKeyDown}
					>
						{this.props.icon}
					</a>
					{this.state.show &&
						this.props.query === 'large' && (
							<div onClick={this.unclicker} className={tooltipWrapper(this.props.palette)}>
								{this.props.render(this.close)}
							</div>
						)}
				</span>
				{this.state.show &&
					this.props.query === Query.small && (
						<div onClick={this.unclicker} className={tooltipWrapper(this.props.palette)}>
							{this.props.render(this.close)}
						</div>
					)}
			</React.Fragment>
		);
	}
}

export default Tooltip;
