import { A, useParams } from "@solidjs/router";
import { createEffect, createResource, For, Suspense } from "solid-js";
import { getUserImages } from "./network";

export function ImagePage() {
    const { imageId } = useParams<{ imageId: string }>();

    const [image] = createResource(async () => {
        const userImages = await getUserImages();

        const currentImage = userImages.find((image) => image.ID === imageId);
        if (currentImage == null) {
            // TODO: this error handling.
            throw new Error("must be valid");
        }

        return currentImage;
    });

    createEffect(() => {
        console.log(image());
    });

    return (
        <Suspense fallback={<>Loading...</>}>
            <A href="/">Back</A>
            <h1 class="text-2xl font-bold">{image()?.Image.ImageName}</h1>
            <img
                src={`http://localhost:3040/image/${image()?.ID}`}
                alt="link"
            />
            <div class="flex flex-col">
                <h2 class="text-xl font-bold">Tags</h2>
                <For each={image()?.Tags ?? []}>
                    {(tag) => <div>{tag.Tag.Tag}</div>}
                </For>

                <h2 class="text-xl font-bold">Locations</h2>
                <For each={image()?.Locations ?? []}>
                    {(location) => (
                        <ul>
                            <li>{location.Name}</li>
                            {location.Address && <li>{location.Address}</li>}
                            {location.Coordinates && (
                                <li>{location.Coordinates}</li>
                            )}
                            {location.Description && (
                                <li>{location.Description}</li>
                            )}
                        </ul>
                    )}
                </For>

                <h2 class="text-xl font-bold">Events</h2>
                <For each={image()?.Events ?? []}>
                    {(event) => (
                        <ul>
                            <li>{event.Name}</li>
                            {event.Location && <li>{event.Location.Name}</li>}
                            {event.Description && <li>{event.Description}</li>}
                        </ul>
                    )}
                </For>
            </div>
        </Suspense>
    );
}
