"use client";

import { type ReactNode } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useAuth } from "@/providers/auth-provider";
import { useToast } from "@/providers/toast-provider";
import { t } from "@/lib/i18n";
import { ROUTE_PERMISSIONS } from "@/lib/permissions";

interface NavItem {
  route: string;
  label: string;
}

const NAV_ITEMS: NavItem[] = [
  { route: "/admin/dashboard", label: t("admin.nav.dashboard") },
  { route: "/admin/users", label: t("admin.nav.users") },
  { route: "/admin/roles", label: t("admin.nav.roles") },
  { route: "/admin/permissions", label: t("admin.nav.permissions") },
  { route: "/admin/viewports", label: t("admin.nav.viewports") },
  { route: "/admin/organization", label: t("admin.nav.organization") },
  { route: "/admin/school", label: t("admin.school.title") },
  { route: "/admin/classes", label: t("admin.nav.classes") },
  { route: "/admin/teachers", label: t("admin.nav.teachers") },
  { route: "/admin/students", label: t("admin.nav.students") },
  { route: "/admin/announcements", label: t("admin.announcements.title") },
  { route: "/admin/invitation-codes", label: t("admin.invitationCodes.title") },
  { route: "/admin/files", label: t("admin.files.title") },
  { route: "/admin/ai-settings", label: t("admin.aiSettings.title") },
  { route: "/admin/audit-logs", label: t("admin.nav.auditLogs") },
  { route: "/admin/system", label: t("admin.nav.system") },
];

export function AdminShell({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const { user, isLoading, isAuthenticated, logout, hasPermission } = useAuth();
  const { show } = useToast();

  if (isLoading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "100vh",
        }}
      >
        <p style={{ color: "var(--color-ink-muted)" }}>
          {t("admin.common.loading")}
        </p>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  const visibleNavItems = NAV_ITEMS.filter((item) => {
    const perm = ROUTE_PERMISSIONS[item.route];
    if (!perm) return true;
    return hasPermission(perm);
  });

  const handleLogout = () => {
    logout();
    show("info", t("admin.auth.logout"));
  };

  return (
    <div
      className="min-h-screen flex"
      style={{ background: "var(--bg-paper)" }}
    >
      {/* 跳过导航链接（A11y WCAG 2.2 AA）*/}
      <a href="#main-content" className="skip-link">
        跳到主内容
      </a>

      {/* 左侧栏：导航树 */}
      <aside
        className="w-56 flex-shrink-0 border-r relative flex flex-col"
        style={{
          borderColor: "var(--color-rule)",
          background: "var(--bg-paper)",
        }}
        aria-label="管理端导航"
      >
        <div className="px-6 py-6">
          <h1
            className="text-xl"
            style={{
              fontFamily: "var(--font-serif)",
              color: "var(--color-ink)",
            }}
          >
            Edu
          </h1>
          <p
            className="text-xs mt-1"
            style={{ color: "var(--color-ink-muted)" }}
          >
            {t("admin.auth.welcome")}
          </p>
        </div>
        <div className="rule-thin mx-6" />

        <nav className="mt-4 px-3 flex-1 overflow-y-auto" aria-label="主导航">
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {visibleNavItems.map((item) => {
              const active =
                pathname === item.route ||
                pathname.startsWith(item.route + "/");
              return (
                <li key={item.route}>
                  <Link
                    href={item.route}
                    className="block px-3 py-2 text-sm transition-colors"
                    style={{
                      color: active
                        ? "var(--color-accent)"
                        : "var(--color-ink)",
                      borderLeft: active
                        ? "2px solid var(--color-accent)"
                        : "2px solid transparent",
                      fontFamily: active
                        ? "var(--font-serif)"
                        : "var(--font-sans)",
                      textDecoration: "none",
                    }}
                  >
                    {item.label}
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        {/* 底部：用户信息 + 登出 */}
        <div
          className="px-6 py-4 border-t"
          style={{ borderColor: "var(--color-rule)" }}
        >
          {user && (
            <div className="mb-2">
              <p className="text-sm" style={{ color: "var(--color-ink)" }}>
                {user.name}
              </p>
              <p
                className="text-xs"
                style={{ color: "var(--color-ink-muted)" }}
              >
                {user.roles.join(", ") || "无角色"}
              </p>
            </div>
          )}
          <button
            onClick={handleLogout}
            className="text-xs uppercase tracking-wide hover:opacity-70"
            style={{
              color: "var(--color-ink-muted)",
              background: "none",
              border: "none",
              cursor: "pointer",
            }}
          >
            {t("admin.auth.logout")}
          </button>
        </div>
      </aside>

      {/* 中间：内容区（纸面） */}
      <main id="main-content" className="flex-1 overflow-auto" role="main">
        {children}
      </main>
    </div>
  );
}
