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

	let {
		onreload
	}: {
		onreload: (item: Application) => void;
	} = $props();

	let dialogElement: HTMLDialogElement;

	let link = $state('');

	async function createApplication() {
		try {
			const r: Application = await post('application/link', {
				text: link
			});
			onreload(r);
            dialogElement.close()
		} catch (e) {
			console.log('Inform the user', e);
		}
	}

	function docKey(e: KeyboardEvent) {
		if (e.ctrlKey && e.code === 'KeyN') {
			dialogElement.showModal();
			e.stopPropagation();
			e.preventDefault();
			return;
		}
	}

	$effect(() => {
		document.addEventListener('keydown', docKey, false);
		return () => {
			document.removeEventListener('keydown', docKey);
		};
	});
</script>

<dialog class="card max-w-[50vw]" bind:this={dialogElement}>
	<form onsubmit={preventDefault(createApplication)}>
		<fieldset>
			<label class="flabel" for="title">Link</label>
			<input class="finput" id="title" bind:value={link} required />
		</fieldset>
	</form>
</dialog>
