import Link from "next/link";
import { redirect } from "next/navigation";
import { isAdminAuthed } from "@/lib/auth";
import { logoutAdmin } from "@/lib/actions/admin-auth";
import { can, type Resource } from "@/lib/permissions";
import AdminSidebarNav from "@/components/admin/AdminSidebarNav";

export default async function AdminDashboardLayout({ children }: { children: React.ReactNode }) {
  const authed = await isAdminAuthed();
  if (!authed) redirect("/iv-manage-84x2/login");

  const allLinks: { href: string; label: string; resource: Resource | null }[] = [
    { href: "/iv-manage-84x2", label: "Dashboard", resource: null },
    { href: "/iv-manage-84x2/orders", label: "Orders", resource: "orders" },
    { href: "/iv-manage-84x2/products", label: "Products", resource: "products" },
    { href: "/iv-manage-84x2/categories", label: "Categories", resource: "categories" },
    { href: "/iv-manage-84x2/inventory", label: "Inventory", resource: "inventory" },
    { href: "/iv-manage-84x2/customers", label: "Customers", resource: "customers" },
    { href: "/iv-manage-84x2/custom-orders", label: "Custom Orders", resource: "custom_orders" },
    { href: "/iv-manage-84x2/discounts", label: "Discounts & Offers", resource: "discounts" },
    { href: "/iv-manage-84x2/payments", label: "Payments", resource: "payments" },
    { href: "/iv-manage-84x2/shipping", label: "Shipping", resource: "shipping" },
    { href: "/iv-manage-84x2/marketing", label: "Marketing", resource: "marketing" },
    { href: "/iv-manage-84x2/reviews", label: "Reviews", resource: "reviews" },
    { href: "/iv-manage-84x2/support", label: "Support", resource: "support" },
    { href: "/iv-manage-84x2/reports", label: "Reports", resource: "reports" },
    { href: "/iv-manage-84x2/website", label: "Website / Pages", resource: "pages" },
    { href: "/iv-manage-84x2/seo", label: "SEO", resource: "seo" },
    { href: "/iv-manage-84x2/settings", label: "Settings", resource: "settings" },
  ];

  const visible = await Promise.all(allLinks.map((l) => (l.resource ? can(l.resource, "view") : Promise.resolve(true))));
  const links = allLinks.filter((_, i) => visible[i]);

  return (
    <div className="mx-auto flex min-h-[80vh] max-w-6xl gap-8 px-4 py-8 sm:px-6 print:block print:max-w-none print:gap-0 print:p-0">
      <aside className="w-48 shrink-0 print:hidden">
        <nav className="sticky top-20 space-y-1">
          <AdminSidebarNav links={links} />
          <Link href="/" className="mt-4 block rounded-md px-3 py-2 text-sm text-stone-400 hover:bg-stone-50">
            ← View storefront
          </Link>
          <form action={logoutAdmin}>
            <button type="submit" className="mt-1 block w-full rounded-md px-3 py-2 text-left text-sm text-stone-400 hover:bg-stone-50">
              Log out
            </button>
          </form>
        </nav>
      </aside>
      <div className="flex-1 min-w-0">{children}</div>
    </div>
  );
}
