<script>
	import * as Table from '$lib/components/ui/table/index';
	import ScrollArea from '$lib/components/ui/scroll-area/scroll-area.svelte';
	import { Checkbox } from '$lib/components/ui/checkbox/index';
	import BookImage from './book-image.svelte';
	import { getBookSelectionState } from '$lib/state/bookSelection.svelte';
	import { getLibraryState } from '$lib/state/library.svelte';

	let { books } = $props();

	const selectedState = getBookSelectionState();
	const libraryState = getLibraryState();
</script>

<Table.Root>
	<Table.Header>
		<Table.Row>
			<Table.Head></Table.Head>
			<Table.Head class="max-w-24 min-w-16">Cover</Table.Head>
			<Table.Head>Title</Table.Head>
			<Table.Head class="max-w-24 min-w-16">Authors</Table.Head>
			<Table.Head>Publisher</Table.Head>
			<Table.Head>Published Date</Table.Head>
			<Table.Head>Pages</Table.Head>
			<Table.Head>Tags</Table.Head>
			<Table.Head>Identifiers</Table.Head>
		</Table.Row>
	</Table.Header>
	<Table.Body>
		{#each books as book (book.id)}
			<Table.Row>
				<Table.Cell
					><Checkbox
						checked={selectedState.isSelected(book.id)}
						onCheckedChange={() => selectedState.toggleSelection(book)}
					/></Table.Cell
				>
				<Table.Cell>
					<BookImage src="/api/{book.cover_image}" />
				</Table.Cell>
				<Table.Cell>{book.title}</Table.Cell>
				<Table.Cell>
					{#each book.authors as author}
						<a
							href="/library/{libraryState.activeLibrary?.id}/view?authors={author.id}"
							class="cs-list hover:underline">{author.name}</a
						> &thinsp;
					{/each}
				</Table.Cell>
				<Table.Cell>{book.publisher}</Table.Cell>
				<Table.Cell>{book.published_date}</Table.Cell>
				<Table.Cell>{book.pages}</Table.Cell>
				<Table.Cell>
					{#each book.tags as tag}
						{tag.name}
					{/each}
				</Table.Cell>
				<Table.Cell>
					{#each Object.entries(book.identifiers) as [name, value] (value)}
						<span class="cs-list">{name}</span> &thinsp;
					{/each}
				</Table.Cell>
			</Table.Row>
		{/each}
	</Table.Body>
</Table.Root>
