import { A, useParams } from "@solidjs/router";
import { createResource, For, Show, type Component } from "solid-js";
import { base, getImageSimilar, type UserImage } from "./network";
import { useSearchImageContext } from "./contexts/SearchImageContext";
import { SearchCard } from "./components/search-card/SearchCard";
import { IconArrowLeft } from "@tabler/icons-solidjs";
import { useSetEntity } from "./WithEntityDialog";

export const Image: Component = () => {
    const { imageId } = useParams<{ imageId: string }>();

    const { imagesWithProperties } = useSearchImageContext();

    const [similarImages] = createResource(() => getImageSimilar(imageId));

    const imageProperties = (): UserImage[] | undefined =>
        Object.entries(imagesWithProperties()).find(
            ([id]) => id === imageId,
        )?.[1];

    const setEntity = useSetEntity();

    return (
        <main class="flex flex-col items-center">
            <nav class="self-start">
                <A href="/">
                    <IconArrowLeft />
                </A>
            </nav>
            <img class="h-1/2" alt="users" src={`${base}/image/${imageId}`} />
            <div class="w-3/4 grid grid-cols-9 gap-2 grid-flow-row-dense py-4">
                <Show when={imageProperties()}>
                    {(image) => (
                        <For each={image()}>
                            {(property) => (
                                <div
                                    onKeyDown={() => setEntity(property)}
                                    onClick={() => setEntity(property)}
                                    class="h-[144px] border relative col-span-3 border-neutral-200 cursor-pointer overflow-hidden rounded-xl"
                                >
                                    <SearchCard item={property} />
                                </div>
                            )}
                        </For>
                    )}
                </Show>
            </div>
            <div class="w-3/4 grid grid-cols-9 gap-2 grid-flow-row-dense py-4">
                <Show when={similarImages()}>
                    {(images) => (
                        <For each={images()}>
                            {(image) => (
                                <img
                                    alt="similar"
                                    class="col-span-3"
                                    src={`${base}/image/${image.ID}`}
                                />
                            )}
                        </For>
                    )}
                </Show>
            </div>
        </main>
    );
};
