import { Product } from "@prisma/client";
import { A, createAsync } from "@solidjs/router";
import { getAnonymousProtectedDbClient } from "~/server/auth/server-auth";
import { Show } from "solid-js";

async function getFirstImg(productId: string) {
  "use server";
  const db = await getAnonymousProtectedDbClient();
  return (
    await db.fileResource.findFirst({
      orderBy: { orderIndex: "asc" },
      where: { linkedProductId: productId }
    })
  )?.path;
}

export default function ProductTile(props: { product: Product }) {
  const { product } = props;
  const firstImgSrc = createAsync(() => getFirstImg(product.id));
  return (
    <div class="max-w-sm p-4">
      <div class="bg-clr-overlay flex h-full flex-col rounded-lg">
        <div class="mb-3 flex items-center">
          <h3 class="mb-2 text-xl font-bold">{product.name}</h3>
        </div>
        <div class="mb-3 flex items-center">
          <div class="group relative mr-3 inline-flex h-3/4 w-full shrink-0 items-center justify-center">
            <div class="absolute bottom-0 hidden w-full p-1 text-center text-xs leading-4 text-red-800 group-hover:block">
              {product.description}
            </div>
            <Show when={firstImgSrc()} fallback={<div class="h-96 w-96"></div>}>
              <img class="max-h-96 max-w-96" src={firstImgSrc()} alt="Image not found!" />
            </Show>
          </div>
        </div>
        <div class="mt-3 flex grow justify-between">
          <p class="inline-flex font-bold">{product.pricePerI}</p>
          <A
            href={"/product-detail/" + product.id}
            class="inline-flex items-center hover:text-blue-600"
          >
            Detail
            <svg
              fill="none"
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              class="ml-2 h-4 w-4"
              viewBox="0 0 24 24"
            >
              <path d="M5 12h14M12 5l7 7-7 7"></path>
            </svg>
          </A>
        </div>
      </div>
    </div>
  );
}