export type ConfirmTone = 'danger' | 'warning' | 'info';

export interface ConfirmOptions {
	title?: string;
	message: string;
	confirmText?: string;
	cancelText?: string;
	tone?: ConfirmTone;
}

interface ConfirmState extends ConfirmOptions {
	open: boolean;
	resolve?: (value: boolean) => void;
}

let state = $state<ConfirmState>({
	open: false,
	title: '',
	message: '',
	confirmText: 'Ya',
	cancelText: 'Batal',
	tone: 'danger'
});

export function getConfirmState() {
	return state;
}

export function confirmDialog(options: ConfirmOptions): Promise<boolean> {
	if (state.open && state.resolve) {
		state.resolve(false);
	}

	return new Promise((resolve) => {
		state = {
			open: true,
			title: options.title ?? 'Konfirmasi',
			message: options.message,
			confirmText: options.confirmText ?? 'Ya',
			cancelText: options.cancelText ?? 'Batal',
			tone: options.tone ?? 'danger',
			resolve
		};
	});
}

export function closeConfirm(result: boolean) {
	if (state.resolve) state.resolve(result);
	state = {
		open: false,
		title: '',
		message: '',
		confirmText: 'Ya',
		cancelText: 'Batal',
		tone: 'danger'
	};
}
