<script lang="ts">
	import { untrack } from 'svelte';
	import { goto } from '$app/navigation';
	import { resolve } from '$app/paths';
	import { X } from '@lucide/svelte';

	import * as Dialog from '$lib/components/ui/dialog/index.js';
	import * as Field from '$lib/components/ui/field/index.js';
	import * as NativeSelect from '$lib/components/ui/native-select/index.js';
	import { Button } from '$lib/components/ui/button';
	import { Switch } from '$lib/components/ui/switch/index';
	import { displaySize, type FileRejectedReason } from '$lib/components/ui/file-drop-zone';
	import BookDropZone from './book-drop-zone.svelte';

	import { getLibraryState } from '$lib/state/library.svelte';
	import { getUploadQueueState } from '$lib/state/upload-queue.svelte';

	let { open = $bindable() }: { open?: boolean } = $props();

	const libraryState = getLibraryState();
	const queue = getUploadQueueState();

	let libraryId = $state<number>(untrack(() => libraryState.activeLibrary!.id));
	let files = $state<File[]>([]);
	let autoUploadOnDrop = $state(true);
	let navigateOnUpload = $state(true);

	const totalSize = $derived(files.reduce((sum, file) => sum + file.size, 0));

	/**
	 * Collected rather than raised one at a time. A folder of a few hundred books
	 * carries covers and notes alongside them, and a toast per rejected file
	 * buries the screen.
	 */
	let rejected = $state<{ name: string; reason: FileRejectedReason }[]>([]);
	let showRejected = $state(false);

	// Start each visit clean — a list left over from last time reads as though it
	// applies to what was just chosen.
	$effect(() => {
		if (open) {
			untrack(() => {
				files = [];
				rejected = [];
				showRejected = false;
				libraryId = libraryState.activeLibrary!.id;
			});
		}
	});

	const onUpload = async (uploadedFiles: File[]) => {
		// Rename to the path relative to the chosen folder, which is what decides
		// how the API groups files into books. Dropped folders already arrive named
		// this way, since the drop zone builds the path while walking them.
		const named = uploadedFiles.map(
			(file) => new File([file], file.webkitRelativePath || file.name, { type: file.type })
		);

		// Same relative path twice is the same file — dropping a folder a second
		// time should not queue everything again.
		const seen = new Set(files.map((file) => file.name));
		files = [...files, ...named.filter((file) => !seen.has(file.name))];

		if (autoUploadOnDrop) await startUpload();
	};

	const onFileRejected = ({ reason, file }: { reason: FileRejectedReason; file: File }) => {
		rejected = [...rejected, { name: file.webkitRelativePath || file.name, reason }];
	};

	/**
	 * Files picked from a folder carry their whole relative path as the name, so
	 * truncating the end would cut off the filename — the only part worth reading.
	 * Split it and let the folder sit on its own, quieter line.
	 */
	function splitPath(path: string) {
		const cut = path.lastIndexOf('/');
		return cut === -1
			? { dir: '', name: path }
			: { dir: path.slice(0, cut), name: path.slice(cut + 1) };
	}

	/**
	 * Hands the books to the queue and closes.
	 *
	 * Nothing is awaited here: the queue lives in the root layout and reports
	 * through the tray, so the import carries on while the library stays usable.
	 */
	function startUpload() {
		if (files.length === 0) return;

		const queued = files;
		const target = libraryId;

		files = [];
		rejected = [];
		open = false;

		queue.enqueue(target, queued, ({ created, firstBook }) => {
			if (created === 0) return;

			const library = libraryState.libraries.find((lib) => lib.id === target);
			if (library) library.total = (library.total ?? 0) + created;

			// Only for a single book. Jumping somewhere after a bulk import would
			// land minutes after the reader moved on.
			if (navigateOnUpload && created === 1 && firstBook) {
				libraryState.setActive(target);
				void goto(resolve('/(root)/(library)/book/[bookId]', { bookId: String(firstBook.id) }));
			}
		});
	}
</script>

<Dialog.Root bind:open>
	<!--
		Wider than the default lg: a folder's worth of rows needs the room.

		overflow-hidden and the min-w-0 on the body below are what keep a long
		filename inside the dialog. Dialog.Content is a grid, and grid and flex
		items default to min-width:auto — they refuse to shrink below their
		content's intrinsic width, so one long name widened the body and pushed it
		straight through the dialog's edge regardless of any truncate further down.
	-->
	<Dialog.Content class="overflow-hidden sm:max-w-2xl">
		<Dialog.Header>
			<Dialog.Title>Add books</Dialog.Title>
			<Dialog.Description>
				Files or a folder. A folder becomes one book per directory.
			</Dialog.Description>
		</Dialog.Header>

		<div class="flex w-full min-w-0 flex-col gap-3">
			<div class="flex flex-col gap-1.5">
				<Field.Label for="library_id">Library</Field.Label>
				<NativeSelect.Root id="library_id" bind:value={libraryId} class="w-48">
					{#each libraryState.libraries as library (library.id)}
						<NativeSelect.Option value={library.id}>{library.name}</NativeSelect.Option>
					{/each}
				</NativeSelect.Root>
			</div>

			<BookDropZone
				{onUpload}
				{onFileRejected}
				accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
			/>

			{#if files.length > 0}
				<div class="flex items-baseline justify-between border-b pb-1 text-sm">
					<span><strong class="tabular-nums">{files.length}</strong> ready to upload</span>
					<span class="font-mono text-xs text-muted-foreground tabular-nums">
						{displaySize(totalSize)}
					</span>
				</div>
			{/if}

			<div class="flex max-h-[300px] min-w-0 flex-col gap-2 overflow-y-auto">
				{#each files as file, idx (file.name)}
					{@const location = splitPath(file.name)}
					<div class="flex min-w-0 items-center justify-between gap-2">
						<!-- flex-1 as well as min-w-0: without a constrained width there is
						     nothing for truncate to act against and the row pushes the dialog wide -->
						<div class="flex min-w-0 flex-1 flex-col">
							<span class="truncate text-sm" title={file.name}>{location.name}</span>
							<span class="flex min-w-0 items-baseline gap-2 text-xs text-muted-foreground">
								{#if location.dir}
									<span class="truncate font-mono" title={location.dir}>{location.dir}</span>
								{/if}
								<span class="shrink-0 tabular-nums">{displaySize(file.size)}</span>
							</span>
						</div>
						<Button
							variant="outline"
							size="icon"
							class="shrink-0"
							onclick={() => (files = files.filter((_, i) => i !== idx))}
						>
							<X />
							<span class="sr-only">Remove {file.name}</span>
						</Button>
					</div>
				{/each}
			</div>

			{#if rejected.length > 0}
				<div class="rounded-md border border-star/50 bg-star/10 p-2 text-sm">
					<div class="flex items-center justify-between gap-2">
						<span>
							{rejected.length}
							{rejected.length === 1 ? 'file was' : 'files were'} skipped
						</span>
						<Button variant="ghost" size="sm" onclick={() => (showRejected = !showRejected)}>
							{showRejected ? 'Hide' : 'Show'}
						</Button>
					</div>
					{#if showRejected}
						<ul class="mt-2 flex max-h-32 min-w-0 flex-col gap-1 overflow-y-auto">
							{#each rejected as entry (entry.name)}
								<li class="flex min-w-0 justify-between gap-2 text-xs text-muted-foreground">
									<span class="min-w-0 flex-1 truncate" title={entry.name}>
										{splitPath(entry.name).name}
									</span>
									<span class="shrink-0">{entry.reason}</span>
								</li>
							{/each}
						</ul>
					{/if}
				</div>
			{/if}

			<div class="flex flex-col gap-2 border-t pt-3">
				<div class="flex items-center gap-2">
					<Switch id="auto-upload-on-drop" bind:checked={autoUploadOnDrop} />
					<Field.Label for="auto-upload-on-drop" class="font-normal">
						Start as soon as books are added
					</Field.Label>
					<Button class="ml-auto w-fit" disabled={files.length === 0} onclick={startUpload}>
						Upload
					</Button>
				</div>
				<div class="flex items-center gap-2">
					<Switch id="navigate-to-book" bind:checked={navigateOnUpload} />
					<Field.Label for="navigate-to-book" class="font-normal">
						Open the book when a single one is added
					</Field.Label>
				</div>
			</div>
		</div>
	</Dialog.Content>
</Dialog.Root>
