<script lang="ts">
	import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
	import { toast } from 'svelte-sonner';
	import {
		cancelImport,
		getImportInfo,
		startImport,
		type ImportInfo
	} from '$lib/services/photoprism';
	import { isAuthenticated } from '$lib/stores/session.svelte';
	import Toolbar from '$lib/components/layout/Toolbar.svelte';

	// PhotoPrism's `/import` root holds uploaded-but-not-yet-indexed files
	// (separate from /originals which is what the timeline reads). The
	// folders endpoint returns the staging tree + counts via headers;
	// kicking off the import is a single POST to /import. Mutations land
	// in originals after PhotoPrism finishes processing — invalidate the
	// originals/folders/config caches so the rest of the UI catches up.
	const importQuery = createQuery<ImportInfo>(() => ({
		queryKey: ['import'],
		queryFn: getImportInfo,
		enabled: isAuthenticated(),
		// Refetch every 5 s while the page is open so progress is visible
		// without the user having to refresh. Cheap call — just headers
		// and a folder list.
		refetchInterval: 5_000
	}));

	const qc = useQueryClient();
	const importMut = createMutation(() => ({
		// `move: true` is the typical workflow — once a file is indexed
		// into originals it doesn't need to linger in the staging area.
		mutationFn: () => startImport({ move: true }),
		onSuccess: (r) => {
			toast.success(r.message ?? 'Import started');
			void qc.invalidateQueries({ queryKey: ['import'] });
			void qc.invalidateQueries({ queryKey: ['photos'] });
			void qc.invalidateQueries({ queryKey: ['folders'] });
		},
		onError: (err) =>
			toast.error(err instanceof Error ? err.message : 'Import failed')
	}));

	const cancelMut = createMutation(() => ({
		mutationFn: cancelImport,
		onSuccess: () => {
			toast.message('Import cancelled');
			void qc.invalidateQueries({ queryKey: ['import'] });
		},
		onError: (err) =>
			toast.error(err instanceof Error ? err.message : 'Cancel failed')
	}));

	const fileCount = $derived(importQuery.data?.files ?? 0);
	const folderCount = $derived(importQuery.data?.folders ?? 0);
	const empty = $derived(fileCount === 0 && folderCount === 0);
</script>

<Toolbar>
	<span class="rounded-md border border-border px-2 py-0.5 text-[11px] text-muted-foreground">
		Inbox
	</span>
	<span class="text-[11px] text-muted-foreground">
		{fileCount} file{fileCount === 1 ? '' : 's'} · {folderCount} folder{folderCount === 1
			? ''
			: 's'}
	</span>
	{#snippet trailing()}
		<button
			type="button"
			class="rounded border border-primary/40 bg-primary/10 px-2 py-0.5 text-xs text-primary hover:bg-primary/20 disabled:opacity-50"
			disabled={empty || importMut.isPending}
			onclick={() => importMut.mutate()}
			title="Index files from the inbox into the main library"
		>
			{importMut.isPending ? 'Importing…' : 'Start import'}
		</button>
		<button
			type="button"
			class="rounded border border-border px-2 py-0.5 text-xs hover:bg-accent disabled:opacity-50"
			disabled={!importMut.isPending}
			onclick={() => cancelMut.mutate()}
		>
			Cancel
		</button>
	{/snippet}
</Toolbar>

<main class="min-h-0 flex-1 overflow-y-auto p-6">
	{#if importQuery.isPending}
		<p class="text-sm text-muted-foreground">Loading inbox…</p>
	{:else if importQuery.isError}
		<p class="text-sm text-destructive">
			Failed to read inbox: {importQuery.error instanceof Error
				? importQuery.error.message
				: 'unknown error'}
		</p>
	{:else if empty}
		<div class="space-y-2 text-sm text-muted-foreground">
			<p>The inbox is empty.</p>
			<p>
				Drop files into <code class="rounded bg-muted px-1">/photoprism/import</code> (the
				bind mount in <code class="rounded bg-muted px-1">docker-compose.photoprism.yml</code>)
				and they'll show up here. Click <strong>Start import</strong> to move them into the
				main library; PhotoPrism indexes them, deduplicates against existing originals, and
				files them under <code class="rounded bg-muted px-1">originals/{'{Y}/{M}'}</code>.
			</p>
		</div>
	{:else}
		<div class="space-y-3">
			<p class="text-sm text-muted-foreground">
				{fileCount} file{fileCount === 1 ? '' : 's'} ready to import across {folderCount} subfolder{folderCount === 1
					? ''
					: 's'}.
			</p>
			{#if importQuery.data && importQuery.data.subfolders.length > 0}
				<!-- PhotoPrism doesn't surface a per-folder file count for
				     /import; we just list the staging subfolders so the
				     user has a sense of what's in there. -->
				<ul class="space-y-1 text-[12px]">
					{#each importQuery.data.subfolders as f (f.Path)}
						<li class="flex items-center gap-2 rounded border border-border px-2 py-1">
							<span class="truncate font-mono">{f.Path || '/'}</span>
						</li>
					{/each}
				</ul>
			{/if}
		</div>
	{/if}
</main>
