<script lang="ts">
	import { type Food, FoodService } from '$lib/database/food'
	import { toast } from 'svelte-sonner'
	import type { Err } from '$lib/types'
	import { foodStore } from '$lib/store/foodStore'

	let item: Food = {
		food: '',
		amount: 0,
		description: ''
	}
	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 [dbFood, err]: [Food, Err] = await FoodService.Create(item)
			name = ''
			amount = ''
			description = ''
			per100 = ''
			per100Edited = false

			if (err) {
				toast.error(err)
				return
			}
			foodStore.update((food) => {
				food.unshift(dbFood)
				return food
			})
		}

		if (!per100Edited)
			FoodService.GetLatestPer100(name.trim()).then((res) => {
				if (res[1])
					// toast.error(res[1])
					return

				per100 = res[0].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>
		<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>
		<td class="px-6 py-4">
		</td>
	</tr>
</template>
