import { db } from "@/lib/db";
import { NavItemRow } from "./NavItemRow";
import { NewNavItemForm } from "./NewNavItemForm";
import { AdminOnlyGate } from "../AdminOnlyGate";

async function getMenuItems(menu: "header" | "footer") {
  return db.navItem.findMany({
    where: { menu, parentId: null },
    orderBy: { order: "asc" },
    include: { children: { orderBy: { order: "asc" } } },
  });
}

export default async function AdminNavigationPage() {
  const [headerItems, footerItems] = await Promise.all([
    getMenuItems("header"),
    getMenuItems("footer"),
  ]);

  return (
    <AdminOnlyGate>
      <div>
        <h1 className="font-heading text-3xl font-semibold text-terracotta">
          Navigation
        </h1>
        <p className="mt-2 text-charcoal/60">
          Manage the Main Navigation and Footer menus. Top-level items with
          submenu links show a hover dropdown on the live site.
        </p>

        <div className="mt-8 flex flex-col gap-12">
          <section>
            <h2 className="font-heading text-xl font-semibold text-charcoal">
              Main Navigation
            </h2>
            <ul className="mt-4 flex flex-col gap-3">
              {headerItems.map((item) => (
                <NavItemRow
                  key={item.id}
                  item={item}
                  topLevelOptions={headerItems.map((i) => ({ id: i.id, label: i.label }))}
                />
              ))}
            </ul>
            {headerItems.length === 0 && (
              <p className="mt-2 text-sm text-charcoal/60">No items yet.</p>
            )}
            <div className="mt-4">
              <NewNavItemForm
                menu="header"
                topLevelOptions={headerItems.map((i) => ({ id: i.id, label: i.label }))}
              />
            </div>
          </section>

          <section>
            <h2 className="font-heading text-xl font-semibold text-charcoal">
              Footer Navigation
            </h2>
            <ul className="mt-4 flex flex-col gap-3">
              {footerItems.map((item) => (
                <NavItemRow
                  key={item.id}
                  item={item}
                  topLevelOptions={footerItems.map((i) => ({ id: i.id, label: i.label }))}
                />
              ))}
            </ul>
            {footerItems.length === 0 && (
              <p className="mt-2 text-sm text-charcoal/60">No items yet.</p>
            )}
            <div className="mt-4">
              <NewNavItemForm
                menu="footer"
                topLevelOptions={footerItems.map((i) => ({ id: i.id, label: i.label }))}
              />
            </div>
          </section>
        </div>
      </div>
    </AdminOnlyGate>
  );
}
