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

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

	let dialogElement: HTMLDialogElement;

	let link = $state('');

	let dialogAddMultiple = $state(false);

	let inputField: HTMLTextAreaElement;

	async function createApplication() {
		try {
			if (dialogAddMultiple) {
				const r: Application[] = await post('application/text', {
					text: link
				});
				for (const app of r) {
					applicationStore.all.push(app);
				}
				if (r.length > 0) {
					onreload(r[0]);
				}
				dialogElement.close();
				link = '';
				return;
			}
			const r: Application = await post('application/link', {
				text: link
			});
			applicationStore.all.push(r);
			onreload(r);
			dialogElement.close();
			link = '';
		} catch (e) {
			console.log('TODO: Inform the user', e);
		}
	}

	function docKey(e: KeyboardEvent) {
		if (e.ctrlKey && e.shiftKey && e.code === 'KeyN') {
			dialogAddMultiple = true;
			dialogElement.showModal();
			e.stopPropagation();
			e.preventDefault();
			window.requestAnimationFrame(() => {
				inputField?.focus();
			});
			return;
		} else if (e.ctrlKey && e.code === 'KeyN') {
			dialogAddMultiple = false;
			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}
	onclose={() => {
		dialogAddMultiple = false;
	}}
>
	<form onsubmit={preventDefault(createApplication)}>
		<fieldset>
			<label class="flabel" for="title"
				>{#if dialogAddMultiple}Email text{:else}Link{/if}</label
			>
			{#if dialogAddMultiple}
				<textarea
					class="finput"
					id="title"
					bind:value={link}
					required
					bind:this={inputField}
				></textarea>
			{:else}
				<input class="finput" id="title" bind:value={link} required />
			{/if}
		</fieldset>
		<div class="flex justify-end">
			{#if dialogAddMultiple}
				<button type="submit" class="btn-primary">Submit</button>
			{/if}
		</div>
	</form>
</dialog>
