import type { VNode } from 'vue';
import type { DropdownButtonItemArgs } from '../dropdown-button/dropdown-button-item';
import type { FormItemWrapperArgs, MarginType } from '../form/form-item-wrapper';
import { Prop, toNative } from 'vue-facing-decorator';
import PowerduckState from '../../app/powerduck-state';
import TsxComponent, { Component } from '../../app/vuetsx';
import FormItemWrapper from '../form/form-item-wrapper';

interface TextAreaArgs extends Omit<FormItemWrapperArgs, 'errorId'> {
	value: string;
	placeholder?: string;
	changed: (newValue: string) => void;
	rows: number;
	maxLength?: number;
	disabled?: boolean;
}

@Component
class TextAreaComponent extends TsxComponent<TextAreaArgs> implements TextAreaArgs {
	@Prop() label!: string | VNode;
	@Prop() labelButtons!: DropdownButtonItemArgs[];
	@Prop() subtitle!: string;
	@Prop() cssClass: string;
	@Prop() disabled!: boolean;
	@Prop() value!: string;
	@Prop() placeholder!: string;
	@Prop() mandatory!: boolean;
	@Prop() marginType?: MarginType;
	@Prop() maxWidth?: number;
	@Prop() wrap!: boolean;
	@Prop() showClearValueButton!: boolean;
	@Prop() hint: string;
	@Prop() rows: number;
	@Prop() maxLength: number;
	@Prop() appendIcon: string;
	@Prop() prependIcon: string;
	@Prop() appendClicked: () => void;
	@Prop() prependClicked: () => void;
	@Prop() changed: (newValue: string) => void;

	private get errorId(): string {
		return `textarea-error-${this.$.uid}`;
	}

	raiseChangeEvent(e) {
		this.populateValidationDeclaration();

		if (this.changed != null) {
			const newValue = e.target.value;
			this.changed(newValue);
		}
	}

	render(h) {
		return (
			<FormItemWrapper
				label={this.label}
				mandatory={this.mandatory}
				cssClass={this.cssClass}
				wrap={this.wrap}
				appendIcon={this.appendIcon}
				prependIcon={this.prependIcon}
				hint={this.hint}
				appendClicked={this.appendClicked}
				marginType={this.marginType}
				prependClicked={this.prependClicked}
				maxWidth={this.maxWidth}
				validationState={this.validationState}
				labelButtons={this.labelButtons}
				subtitle={this.subtitle}
				showClearValueButton={this.showClearValueButton}
				errorId={this.errorId}
			>
				<textarea
					value={this.value}
					onChange={e => this.raiseChangeEvent(e)}
					class={PowerduckState.getFormControlCssClass()}
					placeholder={this.placeholder}
					maxlength={this.maxLength}
					disabled={this.disabled}
					rows={this.rows}
					aria-invalid={this.hasValidationError ? 'true' : undefined}
					aria-describedby={this.hasValidationError ? this.errorId : undefined}
					aria-required={this.mandatory ? 'true' : undefined}
				/>
			</FormItemWrapper>
		);
	}
}

const TextArea = toNative(TextAreaComponent);
export default TextArea;
