<script lang="ts">
	import type { ExtractPayload, Todo as RpcTodo } from '@<@var(context.project.name)>/rpc';
	import { getTodoCollection } from '$lib/todocollectionscontext';

	let { todo }: { todo: ExtractPayload<RpcTodo> } = $props();
	const getInitialTodo = () => todo;
	let todoState = $state<ExtractPayload<RpcTodo>>({ ...getInitialTodo() });
	let commitUpdateTimeoutId: ReturnType<typeof setTimeout> | null = null;

	const todoCollection = getTodoCollection();

	const updateTask = () => {
		if (commitUpdateTimeoutId != null) {
			clearTimeout(commitUpdateTimeoutId);
		}

		commitUpdateTimeoutId = setTimeout(() => {
			todoCollection.update(todoState.id, (draft) => {
				draft.task = todoState.task;
			});
		}, 3000);
	};

	const updateDone = () => {
		todoCollection.update(todoState.id, (draft) => {
			draft.done = todoState.done;
		});
	};

	const del = () => {
		todoCollection.delete(todoState.id || '');
	};
</script>

<div class="flex flex-col items-center gap-2 rounded-md border p-5">
	<input
		class="rounded-md border px-3 py-1 text-center"
		type="text"
		bind:value={todoState.task}
		oninput={updateTask}
	/>
	<span>{new Date(todoState.createdAt || '').toLocaleString()}</span>
	<span>{new Date(todoState.updatesAt || '').toLocaleString()}</span>
	<input type="checkbox" bind:checked={todoState.done} onchange={updateDone} />
	<button class="cursor-pointer rounded-md bg-amber-800 p-1 text-amber-100" onclick={del}>
		delete
	</button>
</div>
