<script lang="ts">
	import { toast } from "svelte-sonner";
	import { main } from "$wails/models";
	import { CreateFood, GetLastPer100 } from "$wails/main/App";
	import { foodStore } from "$lib/store/Energy/foodStore";

	let item: main.Food = {
		food: "",
		amount: 0,
		description: "",
		rowid: 0,
		date: "",
		per100: 0,
		energy: 0,
	};
	let name: string = "";
	let amount: string = "";
	let description: string = "";
	let per100: string = "";
	let per100Edited: boolean = false;
	let per100Element: HTMLTableCellElement;

	async function update(event: KeyboardEvent & { currentTarget: EventTarget & HTMLTableCellElement }) {
		name = name.trim();
		amount = amount.trim();
		description = description.trim();
		per100 = per100.trim();

		if (!per100Edited && event.currentTarget === per100Element) per100Edited = true;

		if (event.key == "Enter") {
			event.preventDefault();
			item.food = name;
			item.description = description;
			item.amount = parseInt(amount);
			item.per100 = parseInt(per100);

			const res = await CreateFood(item);
			name = "";
			amount = "";
			// description = ''
			per100 = "";
			per100Edited = false;

			if (!res.success) {
				toast.error(`failed to create item with error ${res.error}`);
				return;
			}

			foodStore.update((value) => [res.data, ...value]);
		}

		if (!per100Edited)
			GetLastPer100(name.trim()).then((res) => {
				if (res.success) {
					per100 = res.data.toString();
				}
			});
	}
</script>

<template>
	<tr class="border-b border-gray-200 dark:border-gray-700 text-lg font-bold">
		<th
			class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
			scope="row"
		>
		</th>
		<!-- svelte-ignore a11y-autofocus -->
		<td
			bind:innerText={name}
			class:border-[3px]={!name}
			class:border-red-600={!name}
			class="px-6 py-4 overflow-hidden"
			contenteditable="true"
			autofocus
			on:keydown={update}
		>
		</td>
		<td
			bind:innerText={description}
			class="px-6 py-4 bg-gray-50 dark:bg-gray-800 overflow-hidden"
			contenteditable="true"
			on:keydown={update}
		>
		</td>
		<td
			bind:innerText={amount}
			class:border-[3px]={!amount}
			class:border-red-600={!amount}
			class="px-6 py-4 overflow-hidden"
			contenteditable="true"
			on:keydown={update}
		>
		</td>
		<td
			bind:this={per100Element}
			bind:innerText={per100}
			class="px-6 py-4 bg-gray-50 dark:bg-gray-800 overflow-hidden"
			class:border-[3px]={!per100}
			class:border-orange-600={!per100}
			contenteditable="true"
			on:keydown={update}
		>
		</td>
	</tr>
</template>
