import type { VNode } from 'vue';
import { Tooltip } from 'bootstrap';
import { Prop, toNative } from 'vue-facing-decorator';
import TsxComponent, { Component } from '../../app/vuetsx';
import { isNullOrEmpty } from '../../common/utils/is-null-or-empty';

interface TextButtonArgs {
	clicked: (e: any) => void;
	text: string | VNode;
	icon: string;
	tooltip?: string;
	cssClass?: string;
	pulsate?: boolean;
	fontAdjust?: boolean;
	iconOnRight?: boolean;
}

@Component
class TextButtonComponent extends TsxComponent<TextButtonArgs> implements TextButtonArgs {
	@Prop() cssClass!: string;
	@Prop() icon!: string;
	@Prop() text!: string | VNode;
	@Prop() tooltip!: string;
	@Prop() fontAdjust!: boolean;
	@Prop() iconOnRight!: boolean;

	@Prop() clicked: (e: any) => void;
	@Prop() disabled!: boolean;
	@Prop() fullWidth!: boolean;
	@Prop() pulsate!: boolean;

	getCssClass(): string {
		return `text-button${this.cssClass != null ? ` ${this.cssClass}` : ''}${this.pulsate ? ' btn-pulsating' : ''}${this.fontAdjust == true ? ' text-button-font' : ''}`;
	}

	handleButtonClicked(e) {
		this.clicked(e);

		if (!isNullOrEmpty(this.tooltip)) {
			document.querySelector('body > .tooltip')?.remove();
		}
	}

	handleButtonKeydown(e: KeyboardEvent) {
		if (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar') {
			e.preventDefault();
			this.handleButtonClicked(e);
		}
	}

	mounted() {
		if (!isNullOrEmpty(this.tooltip)) {
			try {
				// eslint-disable-next-line no-new
				new Tooltip(this.$el as HTMLElement);
			} catch {}
		}
	}

	render(h) {
		return (
			<span
				onClick={(e) => { this.handleButtonClicked(e); }}
				onKeydown={(e: KeyboardEvent) => { this.handleButtonKeydown(e); }}
				class={this.getCssClass()}
				title={this.tooltip}
				role="button"
				tabindex={this.disabled ? -1 : 0}
				aria-disabled={this.disabled ? 'true' : undefined}
			>
				{!this.iconOnRight
				&& <i class={this.icon} aria-hidden="true"></i>}

				<span>{this.text}</span>

				{this.iconOnRight
				&& <i class={this.icon} aria-hidden="true"></i>}
			</span>
		);
	}
}

const TextButton = toNative(TextButtonComponent);
export default TextButton;
