<script lang="ts">
	import { toast } from 'svelte-sonner'
	import { main } from "$wails/models";
	import { CreateWeight } from '$wails/main/App';
	import { weightStore } from '$lib/store/Weight/weightStore';

	let item: main.Weight = {
		weight: 0,
		rowid: 0,
		date: ''
	}
	let weight: string | null = null

	async function update(event: KeyboardEvent & { currentTarget: (EventTarget & HTMLTableCellElement) }) {
		if (!weight) return
		weight = weight.trim()

		if (event.key == 'Enter') {
			event.preventDefault()
			item.weight = parseFloat(weight)

			if (isNaN(item.weight)) {
				toast.error('Weight must be a number')
				return
			}
			const res = await CreateWeight(item)
			weight = ''
			
			if (!res.success) {
				toast.error(`failed to create weight with error ${res.error}`)
				return
			}

			console.log("update");
			weightStore.update((value) => [res.data, ...value]);
		}
	}
</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>
		<td bind:innerText={weight}
		    class:border-[3px]={!weight}
		    class:border-red-600={!weight}
		    class="px-6 py-4 overflow-hidden"
		    contenteditable="true"
		    autofocus
		    on:keydown={update}>
		</td>
	</tr>
</template>
