import { mkdir, readdir } from "fs/promises";
import path from "path";
import Image from "next/image";
import { redirect } from "next/navigation";
import AdminShell from "@/components/admin/AdminShell";
import { requireAdminSession } from "@/lib/admin/auth";

const uploadDir = path.join(process.cwd(), "public", "uploads", "images");

async function getFiles() {
  await mkdir(uploadDir, { recursive: true });
  return readdir(uploadDir);
}

export default async function AdminMediaPage() {
  if (!await requireAdminSession()) redirect("/admin/login");
  const files = await getFiles();

  return (
    <AdminShell>
      <div className="admin-page-head">
        <p className="eyebrow">Assets</p>
        <h1>Medienverwaltung</h1>
      </div>
      <form className="admin-card admin-upload" action="/api/admin/media" method="post" encType="multipart/form-data">
        <label>Datei hochladen<input name="file" type="file" accept="image/jpeg,image/png,image/webp,application/pdf" /></label>
        <button className="button" type="submit">Datei hochladen</button>
      </form>
      <section className="admin-card">
        <h2>Uploads</h2>
        <div className="media-grid">
          {files.map((file) => {
            const url = `/uploads/images/${file}`;
            return (
              <a key={file} className="media-item" href={url} target="_blank" rel="noreferrer">
                {/\.(png|jpe?g|webp)$/i.test(file)
                  ? <Image src={url} alt={file} width={320} height={220} />
                  : <span>{file}</span>}
              </a>
            );
          })}
          {files.length === 0 && <p className="admin-muted">Noch keine Uploads vorhanden.</p>}
        </div>
      </section>
    </AdminShell>
  );
}
