import ArtworkMetaCard from "@/components/artworks/ArtworkMetaCard";
import { ContextBackButton } from "@/components/artworks/ContextBackButton";
import { prisma } from "@/lib/prisma";
import { cn } from "@/lib/utils";
import Image from "next/image";
import Link from "next/link";

export default async function SingleArtworkPage({ params }: { params: { id: string }; searchParams: Record<string, string | string[] | undefined>; }) {
  const { id } = await params;
  const artwork = await prisma.artwork.findUnique({
    where: {
      id,
    },
    include: {
      file: true,
      gallery: true,
      metadata: true,
      albums: true,
      categories: true,
      colors: { include: { color: true } },
      tags: true,
      variants: true
    }
  })

  if (!artwork) return <div>Artwork with this ID could not be found</div>

  const { width, height } = artwork.variants.find((v) => v.type === "resized") ?? { width: 0, height: 0 }

  const colors =
    artwork.colors?.map((c) => c.color?.hex).filter((hex): hex is string => Boolean(hex)) ?? []

  const gradientColors = colors.length
    ? colors.join(", ")
    : "rgba(0,0,0,0.1), rgba(0,0,0,0.03)"


  return (
    <div className="px-8 py-4">
      <div className="relative w-full min-h-10 flex items-center mb-4">
        <div className="z-10"><ContextBackButton /></div>
        {artwork.name ? (
          <div className="pointer-events-none absolute left-1/2 -translate-x-1/2 text-center">
            <div className="pointer-events-auto"><h1 className="text-2xl font-bold mb-4 py-4">{artwork.name}</h1></div>
          </div>
        ) : null}
      </div>
      <div className="flex flex-col items-center gap-4">
        <div className="group rounded-lg border overflow-hidden hover:shadow-lg transition-shadow bg-background relative">
          <div className="relative w-full bg-muted items-center justify-center"
            style={{ aspectRatio: "4 / 3" }}
          >
            <Link href={`/raw/${artwork.id}`}>
              <Image
                src={`/api/image/resized/${artwork.file.fileKey}.webp`}
                alt={artwork.altText || "Artwork"}
                fill={!width || !height}
                width={width}
                height={height}
                className={cn("object-cover transition duration-300")}
              />
            </Link>
          </div>
        </div>
        <div
          className="rounded-lg"
          style={{
            background: `linear-gradient(135deg, ${gradientColors})`,
          }}
        >
          <ArtworkMetaCard
            gradientColors={gradientColors}
            altText={artwork.altText}
            description={artwork.description}
            categories={artwork.categories}
            tags={artwork.tags}
          />
        </div>
      </div>
    </div >
  );
}