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

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

	let filter = $state('');
	let applications: Application[] = $state([]);

	async function getApplicationList() {
		const app: Application[] = await post('application/list', {});
        applications = app.filter((a) => a.id != application.id);
	}

	$effect(() => {
		getApplicationList();
	});

	async function submit(item: Application) {
		try {
			application.linked_application = item.id;
            application.status = ApplicationStatus.LinkedApplication;
			await put('application/update', application);
			dialog.close();
			onreload(item);
		} catch (e) {
			// Show message to the user
			console.log(e);
		}
	}
</script>

<dialog class="card max-w-[50vw]" bind:this={dialog}>
	<div class="flex">
		<input placeholder="Filter" class="p-2 flex-grow" bind:value={filter} />
		<div>
			{applications.length}
		</div>
	</div>
	<div class="overflow-y-auto overflow-x-hidden flex-grow p-2">
		{#each applications.filter((i) => {
			if (!filter) {
				return true;
			}
			const f = new RegExp(filter, 'ig');

			let x = i.title;

			if (i.company) {
				x = `${x} @ ${i.company}`;
			}

			return x.match(f);
		}) 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 class="text-violet-600 overflow-hidden whitespace-nowrap block max-w-full">
						{item.url}
					</span>
				</button>
			</div>
		{/each}
	</div>
</dialog>
