import { getServerSession } from "next-auth/next";
import { getToken } from "next-auth/jwt";
import { cookies } from "next/headers";
import { authOptions } from "@/lib/auth";
import { redirect } from "next/navigation";
import type { Metadata } from "next";
import AdminSidebarClient from "@/components/AdminSidebarClient";

export const metadata: Metadata = { robots: { index: false, follow: false } };

async function getAdminFromRequest() {
  const session = await getServerSession(authOptions).catch(() => null);
  if (session?.user && (session.user as { role?: string }).role === "ADMIN") {
    return {
      name: session.user.name,
      email: session.user.email,
    };
  }

  // Fallback: cookie JWT del login /api/auth/admin-login
  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((c) => `${c.name}=${c.value}`)
    .join("; ");

  const token = await getToken({
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    req: { headers: { cookie: cookieHeader } } as any,
    secret: process.env.NEXTAUTH_SECRET,
  }).catch(() => null);

  if (token && (token as { role?: string }).role === "ADMIN") {
    return {
      name: (token.name as string) || null,
      email: (token.email as string) || null,
    };
  }

  return null;
}

export default async function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const admin = await getAdminFromRequest();

  if (!admin) {
    redirect("/web/marce");
  }

  return (
    <div className="theme-dark flex min-h-screen bg-black text-white p-4 gap-6">
      <AdminSidebarClient name={admin.name} email={admin.email} />
      <main className="flex-1 glass-panel p-8 overflow-y-auto">{children}</main>
    </div>
  );
}
