import type { Locale } from "@/i18n/routing";

import { and, eq } from "drizzle-orm";
import { getTranslations } from "next-intl/server";

import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { Link } from "@/i18n/navigation";
import { requireAdmin, resolveActiveOrgId } from "@/lib/auth-guards";
import { db } from "@/lib/db";
import { member } from "@/lib/db/schema";

import { AdminNav } from "./nav";

export default async function AdminLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;
  const session = await requireAdmin(locale as Locale);
  const t = await getTranslations("Admin");

  const activeOrganizationId = await resolveActiveOrgId(session);
  if (!activeOrganizationId) {
    // Defensive fallback: admin user with no membership at all. Render the
    // old chrome-less layout so the route still works.
    console.warn(
      `[admin/layout] No active org for admin user ${session.user.id}; falling back to chrome-less layout`,
    );
    return (
      <div className="flex min-h-screen flex-col">
        <header className="border-b">
          <div className="mx-auto flex h-14 w-full max-w-7xl items-center justify-between gap-6 px-6">
            <div className="flex items-center gap-6">
              <Link href="/admin" className="text-sm font-semibold tracking-wide uppercase">
                {t("title")}
              </Link>
              <AdminNav />
            </div>
            <Link href="/dashboard" className="text-xs text-muted-foreground hover:text-foreground">
              {t("backToDashboard")}
            </Link>
          </div>
        </header>
        <main className="mx-auto w-full max-w-7xl flex-1 px-6 py-6">{children}</main>
      </div>
    );
  }

  const [memberRow] = await db
    .select({ role: member.role })
    .from(member)
    .where(and(eq(member.userId, session.user.id), eq(member.organizationId, activeOrganizationId)))
    .limit(1);
  const role = (memberRow?.role ?? "member") as "owner" | "admin" | "member";

  return (
    <DashboardShell session={session} activeOrganizationId={activeOrganizationId} role={role}>
      <header className="border-b">
        <div className="mx-auto flex h-14 w-full max-w-7xl items-center justify-between gap-6 px-6">
          <div className="flex items-center gap-6">
            <Link href="/admin" className="text-sm font-semibold tracking-wide uppercase">
              {t("title")}
            </Link>
            <AdminNav />
          </div>
          <Link href="/dashboard" className="text-xs text-muted-foreground hover:text-foreground">
            {t("backToDashboard")}
          </Link>
        </div>
      </header>
      <main className="mx-auto w-full max-w-7xl flex-1 px-6 py-6">{children}</main>
    </DashboardShell>
  );
}
