<script>
	import { EditSymbol } from '$lib/editSymbol.svelte';
	import EditTransaction from '$lib/editTransaction.svelte';
	let currentTransaction = $state({ budget_id: null, amount: 0, notes: '', out_of_budget: false });
	let { transactions, budgetTransactions, budgets } = $props();
	let editing = $state(false);

	function editNotes(transaction, remaining, budgetTransactions) {
		currentTransaction = transaction;
		currentTransaction.amount = remaining;
		currentTransaction.budgetTransactions = budgetTransactions;
		editing = true;
	}
</script>

<div>
	{#each transactions as transaction}
		{@const applicableBudgets = budgetTransactions.filter(
			(bt) => bt.transaction_id === transaction.id
		)}
		{@const budgetTotal = applicableBudgets.reduce(
			(accumulator, currentValue) => accumulator + Number(currentValue.amount),
			0
		)}
		{@const remaining = transaction.amount - budgetTotal}
		<div
			class=" p-2 {remaining != 0 && !transaction.out_of_budget
				? 'bg-warning-content'
				: ''} {transaction.pending ? 'opacity-50' : ''}"
		>
			<div class="h-full flex flex-row justify-between items-center">
				<div class="h-full flex flex-col md:flex-row justify-between md:items-center md:grow">
					<div>
						<div>{transaction.description}</div>
						<div class="text-xs uppercase font-semibold opacity-60">
							{transaction.date.toDateString()}
						</div>
						{#if !transaction.out_of_budget}
							<div class="text-xs uppercase font-semibold text-left opacity-60">
								In Budget: {budgetTotal.toFixed(2)}
							</div>
							<div class="text-xs uppercase font-semibold text-left opacity-60">
								Remaining {remaining.toFixed(2)}
							</div>
						{:else}
							<div class="text-xs uppercase font-semibold text-left opacity-60">Out of budget</div>
						{/if}
					</div>
					{#if applicableBudgets.length > 0}
						<div class="flex grow flex-col">
							{#each applicableBudgets as budgetTransaction}
								<div class="md:text-right">
									{`${budgetTransaction.budget_name}: ${budgetTransaction.amount}`}
								</div>
							{/each}
						</div>
					{/if}

					<div class="md:text-right text-2xl md:p-4 md:w-35">
						<div class="">
							{transaction.amount}
						</div>
					</div>
				</div>

				<div class="">
					<button
						class="btn btn-square btn-ghost"
						onclick={() => editNotes(transaction, remaining, applicableBudgets)}
					>
						{@render EditSymbol()}
					</button>
				</div>
			</div>
		</div>
	{/each}

	{#if editing}
		<EditTransaction transaction={currentTransaction} close={() => (editing = false)} {budgets} />
	{/if}
</div>
