<script lang="ts">
	import Check from '$lib/icons/Check.svelte';
	import Edit from '$lib/icons/Edit.svelte';
	import Trash from '$lib/icons/Trash.svelte';
	import X from '$lib/icons/X.svelte';
	import { tick } from 'svelte';

	interface ListItem {
		name: string;
		token?: string;
	}

	// props, old syntax
	export let list: ListItem[] = [];
	export let currentName: string;
	export let onSave: (n: string, o: string) => unknown = () => {};
	export let onDelete: (n: string) => unknown = () => {};

	let localName = currentName;
	let isEditing = false;
	let inputRef: HTMLInputElement | null = null;

	$: error = validateName(localName);

	function validateName(name: string): string {
		const trimmed = name?.trim() ?? '';
		if (!trimmed) return 'Name darf nicht leer sein.';
		if (list.some((item) => item.name === trimmed && item.name !== currentName)) {
			return 'Name existiert bereits.';
		}
		return '';
	}

	async function startEdit() {
		isEditing = true;
		await tick();
		inputRef?.focus();
	}

	function cancelEdit() {
		localName = currentName;
		isEditing = false;
	}

	function commitEdit() {
		if (!error && localName != currentName) onSave(localName, currentName);

		isEditing = false;
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Enter') commitEdit();
		if (event.key === 'Escape') cancelEdit();
	}

	function handleDeleteClick() {
		onDelete(currentName);
	}
</script>

<div data-testid="test-nameItemEditor">
	{#if isEditing}
		<input
			data-testid="test-input"
			bind:this={inputRef}
			bind:value={localName}
			onkeydown={handleKeydown}
		/>
		<button
			data-testid="commit-button"
			disabled={!!error || localName === currentName}
			onclick={commitEdit}><Check /></button
		>
		<button data-testid="cancel-button" onclick={cancelEdit}><X /></button>
	{:else}
		<span>{localName}</span>
		<button data-testid="edit-button" onclick={startEdit}><Edit /></button>
		<button data-testid="delete-button" onclick={handleDeleteClick}><Trash /></button>
	{/if}
	{#if error}
		<p class="text-red-500">{error}</p>
	{/if}
</div>
