import Image from "next/image";
import { GalleryForm } from "@/admin/components/GalleryForm";
import { AdminRowActions } from "@/admin/components/AdminRowActions";
import { AdminAutoLayout } from "@/admin/layout/AdminAutoLayout";
import { deleteGalleryImageAction } from "@/lib/actions";
import { isSuperAdmin, requirePermission } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

type AdminGalleryPageProps = {
  searchParams: Promise<{ error?: string }>;
};

const errorMessages: Record<string, string> = {
  image: "Please upload an image or enter an image URL.",
  required: "Please enter at least a title for the gallery image."
};

export default async function AdminGalleryPage({ searchParams }: AdminGalleryPageProps) {
  const session = await requirePermission("gallery");
  const superAdmin = isSuperAdmin(session);
  const params = await searchParams;
  const images = await prisma.galleryImage.findMany({
    orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }]
  });

  return (
    <AdminAutoLayout
      description="Upload visual moments and manage what appears on the public gallery."
      error={params.error}
      errorMessages={errorMessages}
      eyebrow="Gallery"
      title="Gallery Images"
      width="wide"
    >
      <div className="main-layout">
        <GalleryForm />

        <div className="map-panel">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">
                {images.length} item{images.length === 1 ? "" : "s"}
              </span>
              <h2>Current Gallery</h2>
              {superAdmin ? <p className="muted">Super Admin can delete any gallery item.</p> : null}
            </div>
          </div>
          <div className="grid-cards">
            {images.map((image) => (
              <div className="card" key={image.id}>
                <Image
                  alt={image.title}
                  height={180}
                  src={image.imageUrl}
                  style={{ borderRadius: 16, objectFit: "cover", width: "100%" }}
                  unoptimized
                  width={360}
                />
                <h3 style={{ color: "var(--neon-text)", margin: "12px 0" }}>{image.title}</h3>
                <span className="status-badge">{image.approvalStatus}</span>
                <p className="muted">{image.description}</p>
                <AdminRowActions
                  deleteAction={deleteGalleryImageAction}
                  deleteConfirm={`Delete "${image.title}" from gallery?`}
                  deleteId={image.id}
                  viewHref="/gallery"
                  viewLabel="View site"
                />
              </div>
            ))}
            {images.length === 0 ? <p className="admin-empty-state">No gallery images yet.</p> : null}
          </div>
        </div>
      </div>
    </AdminAutoLayout>
  );
}
