import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { deleteGalleryCategory } from '../actions';

export default async function GalleryCategoriesPage({ searchParams }: { searchParams: { error?: string } }) {
  const categories = await prisma.galleryCategory.findMany({ orderBy: { createdAt: 'asc' } });
  const counts = await prisma.galleryPhoto.groupBy({ by: ['categoryId'], _count: true });
  const countFor = (id: string) => counts.find((c) => c.categoryId === id)?._count ?? 0;

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between">
        <h1 className="font-display text-3xl">Gallery categories</h1>
        <Link
          href="/admin/gallery/categories/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add category
        </Link>
      </div>
      <p className="mt-2 text-sm text-muted">
        Used to group photos on the public gallery — separate from your product categories.
      </p>

      {searchParams.error === 'in_use' && (
        <div className="mt-6 border border-splash-orange bg-splash-orange/5 p-4 text-sm">
          Can&apos;t delete that category — there are still photos using it. Move or delete those
          photos first.
        </div>
      )}

      {categories.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No gallery categories yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {categories.map((c) => (
            <div key={c.id} className="flex items-center gap-4 py-4">
              <div className="flex-1">
                <p className="font-medium">{c.name}</p>
                <p className="tag-label mt-0.5">
                  {countFor(c.id)} photo{countFor(c.id) === 1 ? '' : 's'}
                </p>
              </div>
              <form action={deleteGalleryCategory}>
                <input type="hidden" name="id" value={c.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
