<script lang="ts">
	import EmptyFoodComp from '$components/Food/EmptyFoodComp.svelte'
	import FoodComp from '$components/Food/FoodComp.svelte'
	import type { Food } from '$lib/database/food'
	import { GenerateColor } from '$lib/utils'

	export let items: Food[] = []

	let minCal = 1e5
	let maxCal = 0
	for (let item of items) {
		if (!item.energy) continue
		if (item.energy > maxCal) maxCal = item.energy
		if (item.energy < minCal) minCal = item.energy
	}

	const start = '#99ff99'
	const end = '#ff9999'

	function lerp(item: Food) {
		if (!item) return start
		if (!item.energy) return start
		const t = (item.energy - minCal) / (maxCal - minCal)
		const r = parseInt(start.slice(1, 3), 16) * (1 - t) + parseInt(end.slice(1, 3), 16) * t
		const g = parseInt(start.slice(3, 5), 16) * (1 - t) + parseInt(end.slice(3, 5), 16) * t
		const b = parseInt(start.slice(5, 7), 16) * (1 - t) + parseInt(end.slice(5, 7), 16) * t
		return `rgb(${r}, ${g}, ${b})`
	}

	const itemColors: Map<string, string> = new Map<string, string>()

	function getNameColor(item: Food): string {
		if (!item) return GenerateColor()
		if (!item.food) return GenerateColor()
		if (!itemColors.has(item.food)) itemColors.set(item.food, GenerateColor())
		// THERE'S NOTHING UNDEFINED HERE
		// WE GOT RID OF UNDEFINED ON LINE 33
		// ASSHOLE
		// @ts-ignore
		return itemColors.get(item.food)
	}

	const dateColors: Map<string, string> = new Map<string, string>()
	function getDateColor(item: Food): string {
		if (!item) return GenerateColor()
		if (!item.date) return GenerateColor()
		const date = item.date.toString().split(" ")[0]
		if (!date) return GenerateColor()
		if (!dateColors.has(date)) dateColors.set(date, GenerateColor())
		// THERE'S NOTHING UNDEFINED HERE
		// WE GOT RID OF UNDEFINED ON LINE 33
		// ASSHOLE
		// @ts-ignore
		return dateColors.get(date)
	}
</script>

<template>
	<div class="relative flex flex-col h-screen" data-vaul-drawer-wrapper id="page">
		<div class="relative overflow-x-auto shadow-md sm:rounded-lg">
			<table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400">
				<thead class="text-xs text-gray-700 uppercase dark:text-gray-400">
				<tr>
					<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800" scope="col">
						Date
					</th>
					<th class="px-6 py-3" scope="col">
						Food
					</th>
					<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800" scope="col">
						Description
					</th>
					<th class="px-6 py-3" scope="col">
						Amount
					</th>
					<th class="px-6 py-3 bg-gray-50 dark:bg-gray-800" scope="col">
						Cal Per 100
					</th>
					<th class="px-6 py-3" scope="col">
						Energy
					</th>
				</tr>
				</thead>
				<tbody>
				<EmptyFoodComp />
				{#each items as f}
					<FoodComp item="{f}" energyColor="{lerp(f)}" nameColor="{getNameColor(f)}" dateColor="{getDateColor(f)}" />
				{/each}
				</tbody>
			</table>
		</div>
		<div>
		</div>
	</div>
</template>
