<script lang="ts">
	import { onMount } from 'svelte';
	import { pb, currentUser } from '$lib/pocketbase';
	import Counters from '$lib/components/counters.svelte';
	import Action from '$lib/components/Action.svelte';

	type Action = {
		type: string;
		timestamp: string;
	};

	let actions: Action[] = [];

	onMount(async () => {
		await fetchActions();
	});

	async function recordAction(actionType: string) {
		const action = {
			// No longer specifying a timestamp here
			type: actionType,
			timestamp: new Date().toISOString()
		};

		// Send action to PocketBase
		await pb.collection('actions').create(action);

		// Refresh actions list
		await fetchActions();
	}

	async function fetchActions() {
		// Fetch actions for the current day from PocketBase
		const today = new Date().toISOString().split('T')[0];
		const result = await pb.collection('actions').getList<Action>(1, 50, {
			filter: `timestamp >= '${today}'`,
			sort: 'timestamp'
		});

		// Assuming the items are in the 'items' property of the result
		actions = result.items;
	}

	const updateAction = async (event) => {
		const updatedAction = event.detail;
		// Update the action in your PocketBase database
		await pb.collection('actions').update(updatedAction.id, updatedAction);
		// Re-fetch or update the actions array locally
		fetchActions();
	};

	const deleteAction = async (event) => {
		const actionToDelete = event.detail;
		// Delete the action from your PocketBase database
		await pb.collection('actions').delete(actionToDelete.id);
		// Re-fetch or update the actions array locally
		fetchActions();
	};

	$: isLastActionAsleep = actions.length > 0 && actions[actions.length - 1].type === 'asleep';
	$: isLastActionAwake = actions.length > 0 && actions[actions.length - 1].type === 'awake';
	$: isLastActionDiaper = actions.length > 0 && actions[actions.length - 1].type === 'diaper';

    $: sortedActions = [...actions].sort((a, b) => {
        return new Date(b.timestamp) - new Date(a.timestamp);
    });
</script>

<style lang="scss">
    .today__list {
        ul {
            display: flex;
            flex-direction: column;
            //gap: 1rem;
            list-style: none;
        }
        .today__item {
            position: relative;
            padding: 1.5rem 2rem;
            border-radius: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;

            width: 15ch;
            font-size: 2.5rem;
            &:nth-child(odd) {
                background: var(--c-zebra);
            }
        }
    }
</style>

{#if $currentUser}
	<aside>
		{#if isLastActionAsleep}
			<button class="button--awake" on:click={() => recordAction('awake')}>Awake</button>
		{:else}
			{#if !isLastActionAwake}
				<button class="button--awake" on:click={() => recordAction('awake')}>Awake</button>
			{/if}
			<button class="button--asleep" on:click={() => recordAction('asleep')}>Asleep</button>
			<button class="button--food" on:click={() => recordAction('food')}>Food</button>
			<button class="button--diaper" on:click={() => recordAction('diaper')}>Diaper</button>
			{#if isLastActionDiaper}
				<button class="button--poop" on:click={() => recordAction('poop')}>Poop</button>
			{/if}
		{/if}
	</aside>

	<section>
		<h2>Today</h2>
		<div class="today__list">
			<ul>
				{#each sortedActions as action (action.id)}
					<li class="today__item">
						<Action {action} on:update={updateAction} on:delete={deleteAction} />
					</li>
				{/each}
			</ul>
			<Counters {actions} />
		</div>
	</section>
{/if}
