import ArtworkThumbGallery from "@/components/artworks/ArtworkThumbGallery";
import TagFilterDialog from "@/components/artworks/TagFilterDialog";
import { Button } from "@/components/ui/button";
import { prisma } from "@/lib/prisma";
import { ListIcon } from "lucide-react";
import Link from "next/link";

function parseTagsParam(tags: string | string[] | undefined): string[] {
  if (!tags) return [];
  const raw = Array.isArray(tags) ? tags.join(",") : tags;
  return raw
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
}

function expandSelectedWithChildren(
  selectedSlugs: string[],
  tagsForFilter: Array<{
    slug: string;
    children: Array<{ slug: string }>;
  }>
) {
  const bySlug = new Map(tagsForFilter.map((t) => [t.slug, t]));
  const out = new Set(selectedSlugs);

  for (const slug of selectedSlugs) {
    const t = bySlug.get(slug);
    if (!t) continue;
    for (const c of t.children ?? []) out.add(c.slug);
  }

  return Array.from(out);
}

export default async function AnimalStudiesPage({ searchParams }: { searchParams: { tags?: string | string[] } }) {
  const { tags } = await searchParams;

  const selectedTagSlugs = parseTagsParam(tags);
  const tagsForFilter = await prisma.artTag.findMany({
    where: { showOnAnimalPage: true },
    select: {
      id: true,
      name: true,
      slug: true,
      sortIndex: true,
      parentId: true,
      parent: { select: { id: true, name: true, slug: true, sortIndex: true } },
      children: {
        where: { showOnAnimalPage: true },
        select: { id: true, name: true, slug: true, sortIndex: true, parentId: true },
        orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
      },
    },
    orderBy: [{ sortIndex: "asc" }, { name: "asc" }],
  });

  const expandedTagSlugs = expandSelectedWithChildren(selectedTagSlugs, tagsForFilter);

  const artworks = await prisma.artwork.findMany({
    where: {
      categories: { some: { name: "Animal Studies" } },
      published: true,
      ...(expandedTagSlugs.length
        ? { tags: { some: { slug: { in: expandedTagSlugs } } } }
        : {}),
    },
    include: {
      file: true,
      metadata: true,
      tags: true,
      variants: true,
      colors: {
        select: { color: { select: { hex: true } } }
      }
    },
    orderBy: [{ sortKey: "asc" }, { id: "asc" }],
  });

  // console.log(JSON.stringify(artworks, null, 4))

  return (
    <div className="mx-auto w-full max-w-6xl px-4 py-8">
      <header className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div className="space-y-1">
          <h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">
            Animal studies
          </h1>
          <p className="text-sm text-muted-foreground">
            {selectedTagSlugs.length > 0
              ? `Filtered by ${selectedTagSlugs.length} tag${selectedTagSlugs.length === 1 ? "" : "s"}`
              : "Browse all published artworks in this category."}
          </p>
        </div>

        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
          <TagFilterDialog
            tags={tagsForFilter}
            selectedTagSlugs={selectedTagSlugs}
          />

          <Button asChild type="button" variant="secondary" className="h-11 gap-2">
            <Link href="/artworks/animalstudies/index">
              <ListIcon className="h-4 w-4" />
              Animal index
            </Link>
          </Button>
        </div>
      </header>

      <ArtworkThumbGallery items={artworks} fit={{ mode: "fixedWidth", width: 300 }} />
    </div>
  );
}