import { App, Modal } from 'obsidian';

type DialogType = 'alert' | 'confirm' | 'prompt';

export class Dialog extends Modal {
	private type: DialogType;
	private message: string;
	private resolveFn: (value: any) => void;
	private inputValue: string = '';
	private placeholder: string;

	constructor(app: App, type: DialogType, message: string, placeholder = '') {
		super(app);
		this.type = type;
		this.message = message;
		this.placeholder = placeholder;
	}

	open(): Promise<any> {
		return new Promise((resolve) => {
			this.resolveFn = resolve;
			super.open();
		});
	}

	onOpen() {
		const { contentEl } = this;
		contentEl.empty();

		// Создаем сообщение
		contentEl.createEl('div', { text: this.message, cls: 'dialog-message' });

		// Если prompt — добавляем input
		if (this.type === 'prompt') {
			const input = contentEl.createEl('input', {
				type: 'text',
				cls: 'dialog-input',
				attr: { placeholder: this.placeholder }
			}) as HTMLInputElement;

			input.oninput = () => {
				this.inputValue = input.value;
			};

			input.focus();
		}

		// Контейнер для кнопок
		const buttonsDiv = contentEl.createDiv({ cls: 'dialog-buttons' });

		if (this.type === 'alert') {
			// Только OK
			const okBtn = buttonsDiv.createEl('button', { text: 'OK', cls: 'mod-cta' });
			okBtn.onclick = () => {
				this.resolveFn(undefined);
				this.close();
			};
		} else if (this.type === 'confirm' || this.type === 'prompt') {
			// Отмена
			const cancelBtn = buttonsDiv.createEl('button', { text: 'Отмена' });
			cancelBtn.onclick = () => {
				this.resolveFn(this.type === 'prompt' ? null : false);
				this.close();
			};

			// OK
			const okBtn = buttonsDiv.createEl('button', { text: 'OK', cls: 'mod-cta' });
			okBtn.onclick = () => {
				if (this.type === 'prompt') {
					this.resolveFn(this.inputValue);
				} else {
					this.resolveFn(true);
				}
				this.close();
			};
		}
	}

	onClose() {
		this.contentEl.empty();
	}

	// Статические методы для удобства вызова

	static show(app: App, type: DialogType, message: string, placeholder = ''): Promise<any> {
		const dialog = new Dialog(app, type, message, placeholder);
		return dialog.open();
	}

	static alert(app: App, message: string): Promise<void> {
		return Dialog.show(app, 'alert', message);
	}

	static confirm(app: App, message: string): Promise<boolean> {
		return Dialog.show(app, 'confirm', message);
	}

	static prompt(app: App, message: string, placeholder = ''): Promise<string | null> {
		return Dialog.show(app, 'prompt', message, placeholder);
	}
}
