<script lang="ts">
	import type { Weight } from '$lib/database/weight'

	export let item: Weight
	export let dateColor: string

	let weight: string = item.weight.toString()

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

	async function focusOutUpdate() {
		await updateItem()
	}

	async function updateItem() {
		weight = weight.trim()

		item.weight = weight

		const [newItem, err] = await WeightService.Update(item)

		if (newItem && !err) {
			item = newItem
		}
		weight = item.weight
	}
</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">
			{item.weight}
		</td>
	</tr>
</template>
