<script lang="ts">
	import { UpdateFood } from '$wails/main/App';
	import {main} from '$wails/models'
	import { toast } from 'svelte-sonner'

	export let item: main.Food
	export let energyColor: string
	export let nameColor: string
	export let dateColor: string

	let amount: string = item.amount.toString()
	let per100: string = item.per100?.toString() ?? ''
	let description: string = item.description ?? ''
	let name: string = item.food

	async function update(event: KeyboardEvent & { currentTarget: (EventTarget & HTMLTableCellElement) }) {
		if (event.key == 'Enter') {
			event.preventDefault()
			await updateItem()
		}
	}

	async function focusOutUpdate() {
		await updateItem()
	}

	async function updateItem() {
		amount = amount.trim()
		per100 = per100.trim()
		description = description.trim()
		name = name.trim()

		item.food = name
		item.description = description
		item.amount = parseInt(amount)
		item.per100 = parseInt(per100)

		const res = await UpdateFood(item)
		if (!res.success) {
			toast.error(`failed to update food item with error ${res.error}`)
		} else {
			item = res.data
		}
		name = item.food
		description = item.description ?? ''
		amount = item.amount.toString()
		per100 = item.per100?.toString() ?? ''
	}
</script>

<template>
	<tr class="border-b border-gray-200 dark:border-gray-700 font-bold text-lg">
		<th class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap bg-gray-50 dark:text-white dark:bg-gray-800"
		    style="color: {dateColor}"
		    scope="row">
			{item.date}
		</th>
		<td class="px-6 py-4"
		    style="color: {nameColor}"
		    contenteditable="true"
		    bind:innerText={name}
		    on:focusout={focusOutUpdate}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
		    contenteditable="true"
		    bind:innerText={description}
		    on:focusout={focusOutUpdate}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4"
		    contenteditable="true"
		    bind:innerText={amount}
		    on:focusout={focusOutUpdate}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
		    contenteditable="true"
		    bind:innerText={per100}
		    on:focusout={focusOutUpdate}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4" style="color: {energyColor}">
			{item.energy}
		</td>
	</tr>
</template>
