import { getConfig } from './config';
import { SPINNER_ICON_SVG } from './ui';

function getDeleteButton(el: HTMLElement): HTMLButtonElement | null {
	return el.closest('.PDFDraft-Invoice-Delete-Button') as HTMLButtonElement | null;
}

export function initDeleteInvoiceHandler(): void {
	document.addEventListener('click', (e) => {
		const target = e.target as HTMLElement;
		const btn = getDeleteButton(target);
		if (!btn) {
			return;
		}
		e.preventDefault();

		const { i18n } = getConfig();
		const msg = i18n?.confirmDeleteInvoice;
		if (!msg || !window.confirm(msg)) {
			return;
		}

		const url = btn.getAttribute('data-delete-url') ?? '';
		const nonce = getConfig().nonce ?? '';
		if (!url || !nonce) {
			window.alert(i18n?.errorDeleteFailed ?? '');
			return;
		}

		btn.disabled = true;
		btn.setAttribute('aria-busy', 'true');

		// Inline spinner inside the button so narrow side meta boxes don’t clip a WP core
		// `.spinner` inserted after the button (overflow hidden on the metabox).
		const icon = btn.querySelector('.PDFDraft-Invoice-Delete-Icon') as
			| SVGElement
			| null;
		if (icon) {
			icon.style.display = 'none';
		}

		const spinner = document.createElement('span');
		spinner.className = 'PDFDraft-Invoice-Delete-Spinner';
		spinner.setAttribute('aria-hidden', 'true');
		spinner.innerHTML = SPINNER_ICON_SVG;
		btn.appendChild(spinner);

		fetch(url, {
			method: 'DELETE',
			credentials: 'same-origin',
			headers: {
				'X-WP-Nonce': nonce,
			},
		})
			.then(async (res) => {
				if (!res.ok) {
					throw new Error('delete failed');
				}
				window.location.reload();
			})
			.catch(() => {
				window.alert(i18n?.errorDeleteFailed ?? '');
				btn.disabled = false;
				btn.removeAttribute('aria-busy');
				spinner.remove();
				if (icon) {
					icon.style.display = '';
				}
			});
	});
}
