import { Component, For, Show } from "solid-js";
import { useParams } from "@solidjs/router";
import { union, literal, safeParse, InferOutput, parse } from "valibot";
import { useSearchImageContext } from "@contexts/SearchImageContext";
import { SearchCard } from "@components/search-card/SearchCard";

const entityValidator = union([
	literal("event"),
	literal("note"),
	literal("location"),
	literal("contact"),
]);

const EntityGallery: Component<{
	entity: InferOutput<typeof entityValidator>;
}> = (props) => {
	// Just to be doubly sure.
	parse(entityValidator, props.entity);

	// These names are being silly. Entity or Category?
	const { images } = useSearchImageContext();

	const filteredCategories = () =>
		images().filter((i) => i.type === props.entity);

	return (
		<div class="w-full flex flex-col gap-4 capitalize bg-white rounded-xl p-4">
			<h2 class="font-bold text-xl">
				{props.entity}s ({filteredCategories().length})
			</h2>
			<div class="grid grid-cols-3 gap-4">
				<For each={filteredCategories()}>
					{(category) => <SearchCard item={category} />}
				</For>
			</div>
		</div>
	);
};

export const Gallery: Component = () => {
	const params = useParams();
	const validated = safeParse(entityValidator, params.entity);

	return (
		<Show
			when={validated.success}
			fallback={<p>Sorry, this entity is not supported</p>}
		>
			<EntityGallery entity={validated.output as any} />
		</Show>
	);
};
