"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";

import { api, type Session } from "@/lib/api/browser";

/**
 * Role-aware navigation (task 3.4, add-admin-access-control task 9.6).
 *
 * A Host sees everything they need to run their own events; only a Super Admin sees the
 * admin roster. Hiding is courtesy, not enforcement — every one of these routes is
 * independently guarded in FastAPI, so a hand-typed URL gets a 403 rather than a page.
 *
 * What the nav cannot express is the other half of a Host's boundary: scope. Every screen
 * below shows only the events they own, and that is decided by the API's queries, not here.
 */
type NavItem = { href: string; label: string; requires: string; exact?: boolean };

const ITEMS: NavItem[] = [
  { href: "/admin", label: "Dashboard", requires: "view_dashboard", exact: true },
  // Order follows the way the job is actually done: an event exists first, then its guest
  // list, then what gets sent to it. Events therefore leads, ahead of everything scoped to it.
  { href: "/admin/events", label: "Events", requires: "edit_content" },
  // No Import tab: import is a modal on the guest list now (design D6). A tab pointing at
  // /admin/import would follow its redirect and light up Guests — a tab that navigates to a
  // different tab, which reads as a bug rather than a move.
  { href: "/admin/guests", label: "Guests", requires: "view_dashboard" },
  { href: "/admin/messages", label: "Messages", requires: "send_messages" },
  { href: "/admin/reminders", label: "Reminders", requires: "manage_reminders" },
  // Super Admin only. The roster is where scope itself is assigned, so a Host who could
  // reach it could grant themselves every event in the system.
  { href: "/admin/users", label: "Users", requires: "manage_admins" },
  { href: "/admin/qr", label: "QR codes", requires: "generate_qr" },
];

const ROLE_LABEL: Record<string, string> = {
  super_admin: "Super admin",
  host: "Host",
};

export default function AdminNav({ session }: { session: Session }) {
  const pathname = usePathname();
  const router = useRouter();
  const [signingOut, setSigningOut] = useState(false);

  const visible = ITEMS.filter((item) => session.permissions.includes(item.requires));

  async function signOut() {
    setSigningOut(true);
    try {
      await api.signOut();
    } finally {
      // Refresh rather than push: the server layout re-reads the session and redirects,
      // so there is no window where a stale client cache still renders admin data.
      router.replace("/admin/signin");
      router.refresh();
    }
  }

  return (
    <header className="border-b border-stone-200 bg-white">
      <div className="mx-auto flex w-full max-w-6xl flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3 sm:px-6">
        <span className="text-sm font-semibold tracking-tight text-stone-900">RSVP Admin</span>

        <nav aria-label="Admin sections" className="order-3 w-full sm:order-none sm:w-auto">
          {/* Horizontal scroll rather than a hamburger: during wedding week this is used
              one-handed on a phone, and a visible row of tabs beats a hidden menu. */}
          <ul className="-mx-1 flex gap-1 overflow-x-auto pb-1 sm:mx-0 sm:pb-0">
            {visible.map((item) => {
              const active = item.exact
                ? pathname === item.href
                : pathname.startsWith(item.href);
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    aria-current={active ? "page" : undefined}
                    className={`block whitespace-nowrap rounded-md px-3 py-2 text-sm transition-colors ${
                      active
                        ? "bg-stone-900 text-white"
                        : "text-stone-600 hover:bg-stone-100 hover:text-stone-900"
                    }`}
                  >
                    {item.label}
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        <div className="ml-auto flex items-center gap-3 text-sm">
          {/* Reachable by every admin, whatever their role — it is their own account. */}
          <Link
            href="/admin/profile"
            aria-current={pathname === "/admin/profile" ? "page" : undefined}
            className="hidden text-stone-500 underline-offset-2 hover:text-stone-900 hover:underline sm:inline"
          >
            {session.email}
          </Link>
          <span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-900">
            {ROLE_LABEL[session.role] ?? session.role}
          </span>
          <button
            type="button"
            onClick={signOut}
            disabled={signingOut}
            className="rounded-md px-2 py-1 text-stone-600 underline-offset-2 hover:text-stone-900 hover:underline disabled:opacity-50"
          >
            {signingOut ? "Signing out…" : "Sign out"}
          </button>
        </div>
      </div>
    </header>
  );
}
