import type { VNode } from 'vue';
import type { DropdownListOption } from '.';
import type { Language } from '../../common/enums/language';
import type { ValidationState } from '../../common/static-wrappers/interfaces/validation-interface';
import { Prop, toNative } from 'vue-facing-decorator';
import DropdownList from '.';
import TsxComponent, { Component } from '../../app/vuetsx';
import { LanguageUtils } from '../../common/utils/language-utils';

interface LanguagePickerArgs {
	selected: Language | Language;
	mandatory?: boolean;
	label?: string | VNode;
	placeholder?: string;
	validationState?: ValidationState;
	wrap?: boolean;
	changed: (e: { value: Language; code: Language }) => void;
}

@Component
class LanguagePickerComponent extends TsxComponent<LanguagePickerArgs> implements LanguagePickerArgs {
	@Prop() selected: Language | Language;
	@Prop() mandatory!: boolean;
	@Prop() label!: string | VNode;
	@Prop() placeholder!: string;
	@Prop() wrap!: boolean;
	@Prop() changed: (e: { value: Language; code: Language }) => void;

	getOptionList(): DropdownListOption[] {
		return LanguageUtils.getLanguageList().map(p => ({
			id: p.id,
			text: p.text,
		}));
	}

	getSelectedRow(optArr: DropdownListOption[]) {
		if (this.selected == null) {
			return null;
		}

		const searchVal = this.selected as string;
		return optArr.find(p => p.id == searchVal);
	}

	render(h) {
		const optArr = this.getOptionList();

		return (
			<DropdownList
				label={this.label}
				wrap={this.wrap}
				validationState={this.validationState}
				placeholder={this.placeholder}
				options={optArr}
				mandatory={this.mandatory}
				selected={this.getSelectedRow(optArr)}
				changed={(e: DropdownListOption) => {
					if (e?.id == null) {
						this.changed(null);
					} else {
						this.changed({
							code: e.id as Language,
							value: LanguageUtils.getLanguageEnum(e.id as string),
						});
					}
				}}
			/>
		);
	}
}

const LanguagePicker = toNative(LanguagePickerComponent);
export default LanguagePicker;
