<script>
	import { EditSymbol } from '$lib/editSymbol.svelte';
	import { settingsSymbol } from '$lib/settingsSymbol.svelte';
	import { invalidate, invalidateAll } from '$app/navigation';
	import { loadingModal } from '$lib/loadingModal.svelte';
	import { getContext } from 'svelte';
	import TransactionList from '$lib/transactionList.svelte';

	import EditTransaction from '$lib/editTransaction.svelte';
	import { init } from 'echarts';

	let { data } = $props();
	const addToast = getContext('addToast');
	let transactions = $derived(data.transactions);
	let budgets = $derived(data.budgets);
	let budgetTransactions = $derived(data.budgetTransactions);
	let account = $derived(data.account);
	let hide = $derived(account?.hide || false);
	let inTotal = $derived(account?.in_total || false);
	let expanded = $state([]);
	let loading = $state(false);

	let editing = $state(false);

	function editNotes(transaction, remaining) {
		currentTransaction = transaction;
		currentTransaction.amount = remaining;
		editing = true;
	}

	async function saveSettings() {
		loading = true;
		settings_modal.close();
		let res = await fetch(`/api/account/${account.id}`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				hide: $state.snapshot(hide),
				in_total: $state.snapshot(inTotal)
			})
		});
		loading = false;
		invalidateAll();
		if (res.ok) {
			// Optionally, you can refresh the account data or show a success message
		} else {
			console.error('Failed to save settings');
		}
	}
</script>

<div class="flex mb-4">
	<div class="w-128 flex-none justify-bottom">
		<h1 class="text-lg font-semibold">{account?.name}</h1>
	</div>
	<div class="w-64 grow text-lg uppercase font-semibold">{account?.balance}</div>
	<div class="w-14 flex-none text-right">
		<button class="btn btn-square btn-ghost" onclick={() => settings_modal.showModal()}
			>{@render settingsSymbol()}
		</button>
	</div>
</div>
<h1>Transcations</h1>

<TransactionList {budgets} {budgetTransactions} {transactions} />

<dialog id="settings_modal" class="modal">
	<div class="modal-box">
		<form method="dialog">
			<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
		</form>
		<h3>{account?.name}</h3>
		<fieldset class="fieldset bg-base-100 border-base-300 rounded-box w-64 border p-4">
			<legend class="fieldset-legend">Options</legend>
			<label class="label">
				<input type="checkbox" bind:checked={hide} class="toggle" />
				Hide
			</label>
			<label class="label">
				<input type="checkbox" bind:checked={inTotal} class="toggle" />
				Use in total
			</label>
		</fieldset>
		<button onclick={() => saveSettings()} class="btn btn-primary mt-4">Save</button>
	</div>
	<form method="dialog" class="modal-backdrop">
		<button>close</button>
	</form>
</dialog>

{#if loading}
	{@render loadingModal()}
{/if}
