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

	let {
		index = $bindable(),
		onnext
	}: {
		index: number | undefined;
		onnext: () => void;
	} = $props();

	let dialog: HTMLDialogElement;

	const derivedItem: Application | undefined = $derived(applicationStore.all[index ?? -1]);

	async function moveStatus(status_id: string) {
		// Deactivate active item
		try {
			await put('application/status', {
				id: derivedItem?.id,
				status_id: status_id
			});
		} catch (e) {
			// TODO: Show User
			console.log('info data', e);
			return;
		}
		applicationStore.all[index ?? -1].status_id = status_id;
		applicationStore.reset();
		dialog.close();
		onnext();
		return;
	}

	let status: string | null = $state(null);

	let timeoutCount: number = $state(5);
	let timeout: undefined | number = undefined;
	$effect(() => {
		status = localStorage.getItem('expireStatus');
		return () => {
			if (timeout) clearTimeout(timeout);
		};
	});

	export function open() {
		if (dialog) dialog.showModal();
		if (status) {
			timeoutCount = 5;

			function timeoutF() {
				if (timeoutCount === 0) {
					moveStatus(status!);
					timeout = undefined;

					return;
				}
				timeoutCount -= 1;
				timeout = setTimeout(timeoutF, 1000) as unknown as number;
			}

			timeout = setTimeout(timeoutF, 1000) as unknown as number;
		}
	}

	$effect(() => {
		localStorage.setItem('expireStatus', status ?? '');
	});

	// TODO: Auto delete after of 5 secs of inactivity
</script>

<dialog
	class="card"
	bind:this={dialog}
	onclose={() => {
		if (timeout) clearTimeout(timeout);
	}}
>
	<div>
		<div class="text-center py-10">
			<span class="bi bi-exclamation-triangle-fill text-8xl text-orange-400"></span>
		</div>
		<h1 class="text-4xl py-5 text-center">Found Expired</h1>
		<div class="flex justify-center gap-10">
			<button
				class="btn-primary"
				onclick={() => {
					if (timeout) clearTimeout(timeout);
					dialog.close();
				}}
			>
				Ignore
			</button>
			<select bind:value={status} class="py-5">
				{#each statusStore.nodes as node}
					<option value={node.id}>
						{node.name}
					</option>
				{/each}
			</select>
			<button
				class="btn-danger"
				onclick={() => {
					if (status) moveStatus(status);
				}}
			>
				Move ({timeoutCount}) <span class="bi bi-clock-history animate-pulse"></span>
			</button>
		</div>
	</div>
</dialog>
