<script lang="ts">
	import { dndzone } from 'svelte-dnd-action';
	import { flip } from 'svelte/animate';

	interface LinkItem {
		id: string;
		label: string;
		url: string;
		icon: string | null;
	}

	interface Props {
		appId: string;
		initialLinks?: LinkItem[];
	}

	let { appId, initialLinks = [] }: Props = $props();

	const flipDurationMs = 200;

	let links = $state<LinkItem[]>(initialLinks.map((l) => ({ ...l })));
	let saving = $state(false);
	let error = $state<string | null>(null);

	// New link form
	let newLabel = $state('');
	let newUrl = $state('');
	let newIcon = $state('');

	function addLink() {
		if (!newLabel.trim() || !newUrl.trim()) return;

		const tempId = `temp-${Date.now()}`;
		links = [...links, { id: tempId, label: newLabel, url: newUrl, icon: newIcon || null }];
		newLabel = '';
		newUrl = '';
		newIcon = '';
	}

	function removeLink(id: string) {
		links = links.filter((l) => l.id !== id);
	}

	function handleDndConsider(e: CustomEvent<{ items: LinkItem[] }>) {
		links = e.detail.items;
	}

	function handleDndFinalize(e: CustomEvent<{ items: LinkItem[] }>) {
		links = e.detail.items;
	}

	async function saveLinks() {
		saving = true;
		error = null;

		try {
			// First, get existing links from the server to determine what to add/remove
			const existingRes = await fetch(`/api/apps/${appId}/links`);
			const existingData = existingRes.ok ? await existingRes.json() : { data: [] };
			const existingLinks: Array<{ id: string }> = existingData.data ?? [];
			const existingIds = new Set(existingLinks.map((l) => l.id));

			// Delete links that were removed
			for (const existing of existingLinks) {
				if (!links.some((l) => l.id === existing.id)) {
					await fetch(`/api/apps/${appId}/links`, {
						method: 'DELETE',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({ linkId: existing.id })
					});
				}
			}

			// Add new links (those with temp IDs)
			for (let i = 0; i < links.length; i++) {
				const link = links[i];
				if (!existingIds.has(link.id)) {
					await fetch(`/api/apps/${appId}/links`, {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({
							label: link.label,
							url: link.url,
							icon: link.icon,
							order: i
						})
					});
				}
			}

			// Reorder remaining links
			const reorderIds = links
				.filter((l) => existingIds.has(l.id))
				.map((l) => l.id);
			if (reorderIds.length > 0) {
				await fetch(`/api/apps/${appId}/links`, {
					method: 'PATCH',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ linkIds: reorderIds })
				});
			}
		} catch {
			error = 'Failed to save links';
		} finally {
			saving = false;
		}
	}
</script>

<div class="space-y-4">
	<h3 class="text-sm font-semibold text-foreground">Secondary Links</h3>

	{#if error}
		<p class="text-xs text-destructive">{error}</p>
	{/if}

	<!-- Links List (draggable) -->
	{#if links.length > 0}
		<div
			use:dndzone={{ items: links, flipDurationMs, type: 'app-links' }}
			onconsider={handleDndConsider}
			onfinalize={handleDndFinalize}
			class="space-y-2"
		>
			{#each links as link (link.id)}
				<div
					animate:flip={{ duration: flipDurationMs }}
					class="flex items-center gap-2 rounded-md border border-border bg-card p-2"
				>
					<span class="cursor-grab text-muted-foreground">
						<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<line x1="8" y1="6" x2="8" y2="6" />
							<line x1="16" y1="6" x2="16" y2="6" />
							<line x1="8" y1="12" x2="8" y2="12" />
							<line x1="16" y1="12" x2="16" y2="12" />
							<line x1="8" y1="18" x2="8" y2="18" />
							<line x1="16" y1="18" x2="16" y2="18" />
						</svg>
					</span>
					<div class="min-w-0 flex-1">
						<p class="truncate text-sm font-medium text-foreground">{link.label}</p>
						<p class="truncate text-xs text-muted-foreground">{link.url}</p>
					</div>
					<button
						type="button"
						onclick={() => removeLink(link.id)}
						class="flex-shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
					>
						<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
							<line x1="18" y1="6" x2="6" y2="18" />
							<line x1="6" y1="6" x2="18" y2="18" />
						</svg>
					</button>
				</div>
			{/each}
		</div>
	{/if}

	<!-- Add Link Form -->
	<div class="rounded-md border border-dashed border-border p-3">
		<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
			<input
				type="text"
				bind:value={newLabel}
				placeholder="Link label"
				class="rounded-md border border-input bg-background px-2 py-1.5 text-sm text-foreground"
			/>
			<input
				type="url"
				bind:value={newUrl}
				placeholder="https://..."
				class="rounded-md border border-input bg-background px-2 py-1.5 text-sm text-foreground"
			/>
		</div>
		<div class="mt-2 flex items-center gap-2">
			<input
				type="text"
				bind:value={newIcon}
				placeholder="Icon (optional)"
				class="flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-sm text-foreground"
			/>
			<button
				type="button"
				onclick={addLink}
				disabled={!newLabel.trim() || !newUrl.trim()}
				class="rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
			>
				Add
			</button>
		</div>
	</div>

	<!-- Save Button -->
	<button
		type="button"
		onclick={saveLinks}
		disabled={saving}
		class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
	>
		{saving ? 'Saving...' : 'Save Links'}
	</button>
</div>
