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

export default async function AdminGalleryPage() {
  const photos = await prisma.galleryPhoto.findMany({
    include: { category: true },
    orderBy: { createdAt: 'desc' },
  });

  return (
    <div className="mx-auto max-w-3xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between">
        <h1 className="font-display text-3xl">Gallery</h1>
        <Link
          href="/admin/gallery/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add photo
        </Link>
      </div>
      <p className="mt-2 text-sm text-muted">
        Photos of completed work, shown on the public <Link href="/gallery" className="text-clay hover:text-clay-dark">gallery page</Link>.
        Manage the categories under{' '}
        <Link href="/admin/gallery/categories" className="text-clay hover:text-clay-dark">Gallery categories</Link>.
      </p>

      {photos.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No photos yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {photos.map((p) => (
            <div key={p.id} className="flex items-center gap-4 py-4">
              <img src={p.imageDataUrl} alt="" className="h-16 w-16 border border-line object-cover" />
              <div className="flex-1">
                <p className="font-medium">{p.caption || <span className="text-muted">No caption</span>}</p>
                <p className="tag-label mt-0.5">
                  {new Date(p.createdAt).toLocaleDateString(undefined, { dateStyle: 'medium' })}
                </p>
              </div>
              {p.category ? (
                <span className="tag-label rounded-full bg-surface px-3 py-1">{p.category.name}</span>
              ) : (
                <span className="tag-label text-muted">Uncategorized</span>
              )}
              <form action={deleteGalleryPhoto}>
                <input type="hidden" name="id" value={p.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
