<script lang="ts">
	import { type Food, FoodService } from '$lib/database/food'

	export let item: Food
	export let energyColor: string
	export let nameColor: 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) }) {
		amount = amount.trim()
		per100 = per100.trim()
		description = description.trim()
		name = name.trim()

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

			const [newItem, err] = await FoodService.Update(item)
			name = item.food
			description = item.description ?? ''
			amount = item.amount.toString()
			per100 = item.per100?.toString() ?? ''

			if (newItem && !err) {
				item = newItem
			}
		}
	}
</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"
		    scope="row">
			{item.date}
		</th>
		<td class="px-6 py-4"
		    style="color: {nameColor}"
		    contenteditable="true"
		    bind:innerText={name}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
		    contenteditable="true"
		    bind:innerText={description}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4"
		    contenteditable="true"
		    bind:innerText={amount}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4 bg-gray-50 dark:bg-gray-800"
		    contenteditable="true"
		    bind:innerText={per100}
		    on:keydown={update}>
		</td>
		<td class="px-6 py-4" style="color: {energyColor}">
			{item.energy}
		</td>
	</tr>
</template>
