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

	let {
		application,
		dialog = $bindable(),
		onreload
	}: {
		application: Application;
		dialog: HTMLDialogElement;
		onreload: (item: Application) => void;
	} = $props();

	let filter = $state(application.company ? `@ ${application.company}` : '');

	$effect(() => {
		filter = application.company ? `@ ${application.company}` : '';
	});

	async function submit(item: Application) {
		try {
			await post(`application/link/application/${application.id}/${item.id}`, {});
			applicationStore.removeByID(application.id);
			dialog.close();
			onreload(item);
		} catch (e) {
			// TODO: Show message to the user
			console.log(e);
		}
	}

	let internal: Application[] = $state([]);
</script>

<dialog class="card max-w-[50vw]" bind:this={dialog}>
	<ApplicationSearchBar bind:result={internal} bind:filter excludeApplication={application} />
	<div class="overflow-y-auto overflow-x-hidden flex-grow p-2">
		{#each internal as item}
			<div class="card p-2 my-2 bg-slate-100 max-w-full" role="none">
				<button class="text-left max-w-full" type="button" onclick={() => submit(item)}>
					<h2 class="text-lg text-blue-500">
						{item.title}
						{#if item.company}
							<div class="text-violet-800">
								@ {item.company}
							</div>
						{/if}
					</h2>
					<span>
						{statusStore.nodesR[item.status_id].name}
					</span>
				</button>
			</div>
		{/each}
	</div>
</dialog>
