import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import Reveal from '@/components/Reveal';

export default async function GalleryPage({ searchParams }: { searchParams: { category?: string } }) {
  const categories = await prisma.galleryCategory.findMany({ orderBy: { name: 'asc' } });

  const activeSlug = searchParams.category ?? null;
  const activeCategory = activeSlug ? categories.find((c) => c.slug === activeSlug) ?? null : null;

  const photos = await prisma.galleryPhoto.findMany({
    where: activeCategory ? { categoryId: activeCategory.id } : {},
    orderBy: { createdAt: 'desc' },
  });

  const chipClass = (isActive: boolean) =>
    `border px-3 py-1.5 text-xs transition-colors ${
      isActive ? 'border-clay bg-clay text-paper' : 'border-line hover:border-clay hover:text-clay'
    }`;

  return (
    <div className="mx-auto max-w-6xl px-6 py-12">
      <p className="font-script text-3xl text-splash-pink">Our work</p>
      <h1 className="mt-2 font-display text-4xl">Gallery</h1>
      <p className="mt-3 max-w-xl text-muted">
        A look at pieces we&apos;ve made. Browse by category, or see everything.
      </p>

      {categories.length > 0 && (
        <div className="mt-8 flex flex-wrap gap-2">
          <Link href="/gallery" className={chipClass(activeCategory === null)}>
            All
          </Link>
          {categories.map((c) => (
            <Link key={c.id} href={`/gallery?category=${c.slug}`} className={chipClass(activeCategory?.id === c.id)}>
              {c.name}
            </Link>
          ))}
        </div>
      )}

      {photos.length === 0 ? (
        <div className="mt-10 border border-line bg-surface p-12 text-center">
          <p className="font-display text-xl">
            {activeCategory ? 'Nothing in this category yet' : 'Gallery coming soon'}
          </p>
          <p className="mt-2 text-sm text-muted">
            {activeCategory
              ? 'Try another category, or view all.'
              : "We're putting together a collection of our completed work — check back soon."}
          </p>
        </div>
      ) : (
        <Reveal className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {photos.map((p) => (
            <figure key={p.id} className="group flex w-full flex-col overflow-hidden border border-line bg-surface">
              <div className="aspect-square w-full overflow-hidden">
                <img
                  src={p.imageDataUrl}
                  alt={p.caption ?? 'Completed work'}
                  className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                />
              </div>
              {p.caption && (
                <figcaption className="px-4 py-3 text-sm text-muted">{p.caption}</figcaption>
              )}
            </figure>
          ))}
        </Reveal>
      )}
    </div>
  );
}
