import { useSearchImageContext } from "@contexts/SearchImageContext";
import { Component, For } from "solid-js";
import { createVirtualizer } from "@tanstack/solid-virtual";
import { ImageComponent } from "@components/image";
import { chunkRows } from "./chunk";

type ImageOrDate =
	| { type: "image"; ID: string[] }
	| { type: "date"; date: Date };

export const AllImages: Component = () => {
	let scrollRef: HTMLDivElement | undefined;

	const { imagesByDate } = useSearchImageContext();

	const items = () => {
		const items: Array<ImageOrDate> = [];

		for (const { date, images } of imagesByDate()) {
			items.push({ type: "date", date });
			const chunkedRows = chunkRows(3, images);
			for (const chunk of chunkedRows) {
				items.push({ type: "image", ID: chunk.map((c) => c.ImageID) });
			}
		}

		return items;
	};

	const rowVirtualizer = createVirtualizer({
		count: items().length,
		estimateSize: () => 400,
		getScrollElement: () => scrollRef!,
		overscan: 3,
	});

	return (
		<div
			ref={scrollRef}
			class="flex flex-col gap-4 h-[calc(100% - 12px)] overflow-y-auto"
		>
			<div
				class={`h-[${rowVirtualizer.getTotalSize()}px] grid grid-cols-3 gap-4 rounded-xl border border-neutral-200 bg-white p-4`}
			>
				<For each={rowVirtualizer.getVirtualItems()}>
					{(i) => {
						const item = items()[i.index];
						if (item.type === "image") {
							return (
								<For each={item.ID}>{(id) => <ImageComponent ID={id} />}</For>
							);
						} else {
							return (
								<h3 class="col-span-3 font-bold text-2xl">
									{item.date.toDateString()}
								</h3>
							);
						}
					}}
				</For>
			</div>
		</div>
	);
};
