<script lang="ts">
	import { applicationStore, type Application } from '$lib/ApplicationsStore.svelte';
	import { post, preventDefault } from '$lib/utils';

	let {
		dialog = $bindable(),
		onreload,
		id,
		index
	}: {
		dialog: HTMLDialogElement;
		onreload: (item: Application) => void;
		id: string;
		openWindow?: Window | null;
		index?: number;
	} = $props();

	const data = $state({
		url: ''
	});

	let form: HTMLFormElement | undefined = $state();

	async function submit() {
		try {
			const newItem = await post('application/update/url', {
				id,
				...data
			});
			data.url = '';
			dialog.close();
			if (newItem.id !== applicationStore.all[index ?? -1].id) {
				applicationStore.removeByID(applicationStore.all[index ?? -1].id);
			}
			onreload(newItem);
		} catch (e) {
			// Show message to the user
			console.log(e);
		}
	}

	let hasExtension = $state(false);

	$effect(() => {
		function onMessage(e: MessageEvent) {
			if (dialog.open && e.data.type === 'MY_GET_URL_R') {
				if (e.data.error) {
					if (e.data.data.length === 0) {
						console.log('TODO inform user to mark page');
					} else {
						console.log('TODO inform use to unmark page');
					}
					return;
				}
				if (!e.data.url) return;
				data.url = e.data.url ?? '';
				window.requestAnimationFrame(() => {
					if (!form?.reportValidity()) {
						return;
					}
					submit();
				});
			} else if (e.data.type === 'HAS_EXTENSION') {
				hasExtension = true;
			}

			if (!hasExtension) {
				window.postMessage({ type: 'HAS_EXTENSION_Q' });
			}
		}

		window.addEventListener('message', onMessage);
		return () => {
			window.removeEventListener('message', onMessage);
		};
	});

	function askForUrl() {
		window.postMessage({ type: 'MY_GET_URL' });
	}
</script>

<dialog class="card" bind:this={dialog}>
	<form bind:this={form} onsubmit={preventDefault(submit)}>
		<fieldset>
			<label class="flabel" for="text">Url</label>
			<textarea
				class="finput min-w-96 min-h-96"
				id="text"
				bind:value={data.url}
				onkeydown={(e) => {
					if (e.key === 'Enter' && data.url === '' && hasExtension) {
						e.preventDefault();
						askForUrl();
						return;
					}
				}}
			></textarea>
		</fieldset>
		<div class="btns">
			<button type="submit" class="btn-confirm">Update</button>
			{#if hasExtension}
				<button type="button" class="btn-confirm" onclick={askForUrl}>Get Url</button>
			{/if}
		</div>
	</form>
</dialog>
