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

	import { put, preventDefault, post, get, deleteR } from '$lib/utils';
	import { onMount } from 'svelte';
	import ExtractTextDialog from './ExtractTextDialog.svelte';
	import Flair from '../flair/Flair.svelte';
	import NewUrlDialog from './NewUrlDialog.svelte';
	import { userStore } from '$lib/UserStore.svelte';

	let activeItem: Application | undefined = $state();

	let extractTokens: HTMLDialogElement;
	let changeUrl: HTMLDialogElement;

	let preparingToDrop = $state(false);

	async function activate(item?: Application) {
		if (!item) {
			return;
		}
		if (activeItem && activeItem.id !== item.id && activeItem.status === 1) {
			// Deactivate active item
			try {
				await put('application/status', {
					id: activeItem.id,
					status: 0
				});
			} catch (e) {
				// Show User
				console.log('info data', e);
				return;
			}
		}

		if (item.status === 0) {
			openWindow(item.url);
		}

		try {
			await put('application/status', {
				id: item.id,
				status: ApplicationStatus.WorkingOnIt
			});
			activeItem = await get('application/active');
			if (!activeItem?.unique_url) {
				window.requestAnimationFrame(() => {
					changeUrl.showModal();
				});
			}
		} catch (e) {
			// Show User
			console.log('info data', e);
		}
		applicationStore.loadApplications(true);
	}

	function openWindow(url: string) {
		if (!url.startsWith('https://')) {
			url = `https://${url}`;
		}

		window.open(
			url,
			'new window',
			`location,height=${window.screen.height},width=${window.screen.width},scrollbars,status,toolbar,menubar,popup`
		);
	}

	async function loadActive() {
		try {
			activeItem = await get('application/active');
			if (activeItem?.unique_url === null) {
				changeUrl.showModal();
			}
		} catch (e) {
			// Show User
			console.log('info data', e);
		}
	}

	onMount(() => {
		userStore.checkLogin();
		loadActive();
	});

	async function moveStatus(status: number) {
		if (!activeItem) return;
		// Deactivate active item
		try {
			await put('application/status', {
				id: activeItem.id,
				status: status
			});
		} catch (e) {
			// Show User
			console.log('info data', e);
			return;
		}
		applicationStore.loadApplications(true);
		activeItem = undefined;
		//openedWindow?.close();
		//openedWindow = undefined;
	}

	async function remove() {
		if (!activeItem) return;
		// Deactivate active item
		try {
			await deleteR(`application/${activeItem.id}`);
		} catch (e) {
			// Show User
			console.log('info data', e);
			return;
		}
		applicationStore.loadApplications(true);
		activeItem = undefined;
		//openedWindow?.close();
		//openedWindow = undefined;
	}

	async function save() {
		try {
			await put('application/update', activeItem);
		} catch (e) {
			// Show User
			console.log('info data', e);
		}
	}

	async function resetUrl() {
		try {
			activeItem = await post(`application/reset/url/${activeItem?.id}`, {});
		} catch (e) {
			// Show User
			console.log('info data', e);
		}
	}

	let drag = $state(true);

	const statusMapping: string = $derived(
		(ApplicationStatusMaping[
			activeItem?.status as (typeof ApplicationStatus)[keyof typeof ApplicationStatus]
		] as string) ?? ''
	);
</script>

<div class="flex flex-col w-full gap-2 min-w-0" role="none">
	{#if activeItem && (!applicationStore.dragging || applicationStore.dragging?.id === activeItem.id)}
		<div
			draggable={drag}
			ondrag={() => {
				applicationStore.dragStart(activeItem);
			}}
			ondragend={() => {
				window.requestAnimationFrame(() => {
					applicationStore.dragEnd();
				});
			}}
			role="none"
			class="flex flex-col p-2 h-full gap-2 card min-w-0 flex-grow"
		>
			<div class="w-full">
				{#if activeItem.status != 1}
					<div class="bg-danger text-white p-2 rounded-lg text-lg font-bold">
						{statusMapping}
					</div>
				{/if}
				<fieldset>
					<label class="flabel" for="title">Title</label>
					<input class="finput" id="title" bind:value={activeItem.title} onchange={save} />
				</fieldset>
				<fieldset>
					<label class="flabel" for="payrange">Pay Range</label>
					<input class="finput" id="payrange" bind:value={activeItem.payrange} onchange={save} />
				</fieldset>
				<fieldset
					draggable="false"
					onmouseenter={() => (drag = false)}
					onmouseleave={() => (drag = true)}
					class="max-w-full min-w-0 overflow-hidden"
				>
					<div class="flabel">Url</div>
					<div class="finput bg-white w-full break-keep">
						{activeItem.url}
					</div>
				</fieldset>
				{#if activeItem.unique_url}
					<fieldset
						draggable="false"
						onmouseenter={() => (drag = false)}
						onmouseleave={() => (drag = true)}
					>
						<div class="flabel">Unique Url</div>
						<div class="finput bg-white">
							{activeItem.unique_url}
						</div>
					</fieldset>
				{/if}
				<div>
					<div class="flabel">Tags</div>
					<div class="flex gap-2 flex-wrap">
						{#each activeItem.flairs as item}
							<Flair
								{item}
								allowDelete
								application={activeItem}
								updateApplication={(item) => (activeItem = item)}
							/>
						{/each}
					</div>
				</div>
				<fieldset>
					<label class="flabel" for="extra">Extra Info</label>
					<textarea class="finput" id="extra" bind:value={activeItem.extra_data} onchange={save}
					></textarea>
				</fieldset>
			</div>
			<div class="flex btns">
				<button
					class="btn-confirm"
					onclick={() => {
						openWindow(activeItem!.url);
					}}
				>
					Open
				</button>
				<button
					class="btn-primary"
					onclick={() => window.open(`/cv?id=${activeItem!.id}`, '_blank')}
				>
					Open CV
				</button>
				<button class="btn-primary" onclick={() => extractTokens.showModal()}>
					Extract Flair
				</button>
				{#if activeItem.original_url == null}
					<button class="btn-primary" onclick={() => changeUrl.showModal()}> Update Url </button>
				{/if}
				{#if activeItem.original_url != null}
					<button class="btn-danger" onclick={resetUrl}> Reset Url </button>
				{/if}
			</div>
		</div>
		{#if applicationStore.dragging}
			<div class="flex w-full flex-grow rounded-lg p-1 gap-2">
				<!-- Ignore -->
				<div
					class="grid place-items-center w-full card p-2 rounded-lg"
					role="none"
					ondragover={preventDefault(() => {})}
					ondragenter={preventDefault(() => {})}
					ondrop={() => {
						moveStatus(ApplicationStatus.Ignore);
					}}
				>
					<span
						class="bi bi-trash-fill text-7xl absolute"
						class:animate-bounce={applicationStore.dragging}
					></span>
					<span class="bi bi-trash-fill text-7xl opacity-0"></span>
					<div class="text-xl">Drop Application Ignore it.</div>
				</div>

				<!-- Expired -->
				<div
					class="grid place-items-center w-full card p-2 rounded-lg"
					role="none"
					ondragover={preventDefault(() => {})}
					ondragenter={preventDefault(() => {})}
					ondrop={() => {
						moveStatus(ApplicationStatus.Expired);
					}}
				>
					<span
						class="bi bi-clock-fill text-7xl text-orange-500 absolute"
						class:animate-bounce={applicationStore.dragging}
					></span>
					<span class="bi bi-clock-fill text-7xl text-orange-500 opacity-0"></span>
					<div class="text-orange-500 text-xl">Mark as expired.</div>
				</div>

				<!-- Repeated -->
				<div
					class="grid place-items-center w-full card p-2 rounded-lg"
					role="none"
					ondragover={preventDefault(() => {})}
					ondragenter={preventDefault(() => {})}
					ondrop={() => {
						remove();
					}}
				>
					<span
						class="bi bi-trash-fill text-7xl text-danger absolute"
						class:animate-bounce={applicationStore.dragging}
					></span>
					<span class="bi bi-trash-fill text-7xl text-danger opacity-0"></span>
					<div class="text-danger text-xl">This is repeated</div>
				</div>

				<!-- Applyed -->
				<div
					class="grid place-items-center w-full card p-2 rounded-lg"
					role="none"
					ondragover={preventDefault(() => {})}
					ondragenter={preventDefault(() => {})}
					ondrop={async () => {
						await moveStatus(ApplicationStatus.Applyed);
						applicationStore.loadAplyed(true);
					}}
				>
					<span
						class="bi bi-server text-7xl text-confirm absolute"
						class:animate-bounce={applicationStore.dragging}
					></span>
					<span class="bi bi-server text-7xl text-confirm opacity-0"></span>
					<div class="text-confirm text-xl">Apply</div>
				</div>

				<!-- Rejected -->
				<div
					class="grid place-items-center w-full card p-2 rounded-lg"
					role="none"
					ondragover={preventDefault(() => {})}
					ondragenter={preventDefault(() => {})}
					ondrop={() => {
						moveStatus(ApplicationStatus.ApplyedButSaidNo);
					}}
				>
					<span
						class="bi bi-fire text-danger text-7xl absolute"
						class:animate-bounce={applicationStore.dragging}
					></span>
					<span class="bi bi-fire text-7xl text-danger opacity-0"></span>
					<div class="text-danger text-xl">I was rejeted :(.</div>
				</div>
			</div>
		{/if}
	{:else}
		<div
			class="p-2 h-full w-full gap-2 flex-grow card grid place-items-center"
			ondragover={(e) => {
				e.preventDefault();
			}}
			ondragenter={preventDefault(() => {})}
			ondrop={() => {
				activate(applicationStore.dragging);
			}}
			role="none"
		>
			<div class="text-center relative">
				<span
					class="bi bi-layers-fill text-7xl text-white absolute"
					class:animate-bounce={applicationStore.dragging}
				></span>
				<span class="bi bi-layers-fill text-7xl text-white opacity-0"></span>
				<div class="text-white text-xl">Drop Application To Apply To.</div>
			</div>
		</div>
	{/if}
</div>

<ExtractTextDialog id={activeItem?.id ?? ''} bind:dialog={extractTokens} onreload={loadActive} />

{#if !activeItem?.original_url}
	<NewUrlDialog
		id={activeItem?.id ?? ''}
		bind:dialog={changeUrl}
		onreload={(item) => (activeItem = item)}
	/>
{/if}
