import Link from "next/link";
import { redirect } from "next/navigation";
import { desc } from "drizzle-orm";
import { db } from "@db/client";
import { events } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { getAdminAlbums } from "@db/queries/gallery-db";
import { Images, ImagePlus } from "lucide-react";
import GalleryManager, { type AdminAlbum, type LinkableEvent } from "./gallery-manager";
import { PageHeader } from "@/components/ui";

export const metadata = { title: "Gallery · Admin" };

export default async function AdminGalleryPage() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const [adminAlbums, eventRows] = await Promise.all([
    getAdminAlbums(),
    db.select({ id: events.id, title: events.title, startsAt: events.startsAt }).from(events).orderBy(desc(events.startsAt)),
  ]);

  const albums: AdminAlbum[] = adminAlbums.map((a) => ({
    ...a,
    gallery_photos: [...a.gallery_photos].sort((x, y) => x.sort_order - y.sort_order),
  }));

  const linkableEvents: LinkableEvent[] = eventRows.map((e) => ({
    id: e.id,
    title: e.title,
    starts_at: e.startsAt.toISOString(),
  }));

  return (
    <div className="max-w-3xl space-y-6">
      <PageHeader
        icon={Images}
        title="Gallery"
        description="Albums and photos shown on the public gallery. Link an album to an event to show it on that event's page."
        actions={
          <Link
            href="/admin/gallery/submissions"
            className="inline-flex items-center gap-1.5 text-sm font-medium text-brand-green-h hover:opacity-80"
          >
            <ImagePlus className="h-4 w-4" />
            Review submissions
          </Link>
        }
      />
      <GalleryManager initial={albums} events={linkableEvents} />
    </div>
  );
}
