import Link from "next/link";
import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { AdminNav } from "@/components/admin/AdminNav";
import { logoutAction } from "@/app/admin/actions";
import { getSession } from "@/lib/auth";
import { getSettings } from "@/lib/cms";

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

export default async function AdminDashboardLayout({
  children,
}: {
  children: ReactNode;
}) {
  const session = await getSession();
  if (!session) redirect("/admin/login");

  const settings = await getSettings();

  return (
    <div className="min-h-screen bg-mint">
      {/* Mobile top bar */}
      <div className="flex items-center justify-between bg-teal-ink px-5 py-4 lg:hidden">
        <Link href="/admin" className="font-display text-lg font-bold text-white">
          S & G <span className="text-amber">Admin</span>
        </Link>
        <form action={logoutAction}>
          <button
            type="submit"
            className="rounded-full border border-white/30 px-3.5 py-1.5 text-xs font-semibold text-white/85 transition-colors hover:bg-white/10"
          >
            Sign out
          </button>
        </form>
      </div>
      <div className="border-b border-white/10 bg-teal-ink px-4 py-3 lg:hidden">
        <AdminNav />
      </div>

      <div className="mx-auto flex w-full max-w-7xl gap-8 px-4 py-6 lg:px-8 lg:py-10">
        {/* Sidebar */}
        <aside className="hidden w-64 shrink-0 lg:block">
          <div className="sticky top-10 rounded-2xl bg-teal-ink p-6 text-white">
            <Link href="/admin" className="font-display text-xl font-bold">
              S & G <span className="text-amber">Admin</span>
            </Link>
            <p className="mt-1 text-xs text-white/55">{settings.brandName}</p>
            <p className="mt-4 truncate rounded-lg bg-white/10 px-3 py-2 text-xs text-white/75">
              {session.email}
            </p>
            <div className="mt-6">
              <AdminNav />
            </div>
            <div className="mt-8 space-y-2 border-t border-white/15 pt-6">
              <Link
                href="/"
                className="block rounded-xl px-4 py-2.5 text-sm font-medium text-white/75 transition-colors hover:bg-white/10 hover:text-white"
              >
                View website
              </Link>
              <form action={logoutAction}>
                <button
                  type="submit"
                  className="w-full rounded-xl px-4 py-2.5 text-left text-sm font-medium text-white/75 transition-colors hover:bg-coral hover:text-white"
                >
                  Sign out
                </button>
              </form>
            </div>
          </div>
        </aside>

        {/* Content */}
        <main className="min-w-0 flex-1">{children}</main>
      </div>
    </div>
  );
}
