"use client";

import { useEffect } from "react";
import { STAFF_SIDE_ROLES } from "@/lib/constants";
import { useRouter } from "next/navigation";
import { useLang } from "@/context/LanguageContext";
import { PanelShell, centralNavIcons } from "@/components/PanelShell";
import { PageLoader } from "@/components/ui";
import { useApi } from "@/lib/client";
import { audienceForRole } from "@/lib/menu-access";
import {
  IconAlertTriangle,
  IconAward, IconInfo,
  IconBell,
  IconCalendar,
  IconCard,
  IconClipboard,
  IconClock,
  IconDollar,
  IconUser,
  IconUserCheck,
  IconShield,
} from "@/components/icons";

interface Me {
  user: {
    id: number;
    name: string;
    email: string | null;
    username: string | null;
    role: string;
    isIdentityManager?: boolean;
    institution: { id: number; name: string; type: string; status: string; logo?: string | null } | null;
  } | null;
  /** subscription menu access — hidden sidebar menus per audience */
  menuAccess?: { hidden: Record<string, string[]> };
}

export default function MeLayout({ children }: { children: React.ReactNode }) {
  const { t } = useLang();
  const router = useRouter();
  const { data, loading, error } = useApi<Me>("/api/auth/me");

  // Invalid/stale session (cookie already cleared by the API) → back to login
  useEffect(() => {
    if (!loading && (error || data?.user == null)) {
      router.replace("/login");
    }
  }, [loading, error, data, router]);

  if (loading) return <PageLoader text={t.common.loading} />;
  if (!data?.user) return <PageLoader text={t.common.sessionExpired} />;

  const isStudentView = data.user.role === "STUDENT" || data.user.role === "PARENT";

  const allNav: {
    href: string;
    label: string;
    icon: React.ComponentType<{ className?: string }>;
    roles?: string[];
    /** subscription menu-access key (src/lib/menu-access.ts) */
    menuKey?: string;
    external?: boolean;
    group?: string;
  }[] = [
    // Items keep the original menu sequence; `group` only inserts a sidebar
    // section header above the first item of each run (per visible role).
    { href: "/me", label: t.common.dashboard, icon: centralNavIcons.dashboard, group: t.navGroups.general },
    // Student/parent self-service modules (unlocked by their credentials)
    { href: "/me/results", label: t.me.navResults, icon: IconAward, group: t.navGroups.academics, roles: ["STUDENT", "PARENT"], menuKey: "results" },
    { href: "/me/exams", label: t.me.navExams, icon: IconCalendar, group: t.navGroups.academics, roles: ["STUDENT", "PARENT"], menuKey: "exams" },
    { href: "/me/schedule", label: t.me.navSchedule, icon: IconClock, group: t.navGroups.academics, roles: ["STUDENT", "PARENT"], menuKey: "schedule" },
    { href: "/guide", label: t.guide.navLabel, icon: IconInfo, external: true, group: t.navGroups.academics },
    { href: "/me/attendance", label: t.me.navAttendance, icon: IconUserCheck, group: t.navGroups.academics, roles: ["STUDENT", "PARENT", ...STAFF_SIDE_ROLES], menuKey: "attendance" },
    { href: "/me/attendance-take", label: t.me.navTakeAttendance, icon: IconUserCheck, group: t.navGroups.academics, roles: [...STAFF_SIDE_ROLES], menuKey: "attendanceTake" },
    { href: "/me/fees", label: t.me.navFees, icon: IconDollar, group: t.navGroups.finance, roles: ["STUDENT", "PARENT"], menuKey: "fees" },
    // Teacher/staff self-service modules
    { href: "/me/marks", label: t.me.navMarks, icon: IconClipboard, group: t.navGroups.academics, roles: [...STAFF_SIDE_ROLES], menuKey: "marks" },
    { href: "/me/leaves", label: t.me.navLeaves, icon: IconCalendar, group: t.navGroups.work, roles: [...STAFF_SIDE_ROLES], menuKey: "leaves" },
    { href: "/me/payroll", label: t.me.navPayroll, icon: IconDollar, group: t.navGroups.work, roles: [...STAFF_SIDE_ROLES], menuKey: "payroll" },
    { href: "/me/lesson-plans", label: t.me.navLessonPlans, icon: IconClipboard, group: t.navGroups.work, roles: [...STAFF_SIDE_ROLES], menuKey: "lessonPlans" },
    // Shared member modules
    { href: "/me/notices", label: t.me.navNotices, icon: IconBell, group: t.navGroups.campus, roles: ["STUDENT", "PARENT", ...STAFF_SIDE_ROLES], menuKey: "notices" },
    { href: "/me/complaints", label: t.me.navComplaints, icon: IconAlertTriangle, group: t.navGroups.campus, roles: ["STUDENT", "PARENT", ...STAFF_SIDE_ROLES], menuKey: "complaints" },
    { href: "/me/idcard", label: t.me.navIdCard, icon: IconCard, group: t.navGroups.campus, roles: ["STUDENT", "PARENT"], menuKey: "idcard" },
    { href: "/me/verify", label: t.verifyPage.navLabel, icon: IconShield, group: t.navGroups.account, roles: ["STUDENT", "PARENT", ...STAFF_SIDE_ROLES] },
    { href: "/me/profile", label: t.me.navProfile, icon: IconUser, group: t.navGroups.account, roles: ["STUDENT", "PARENT", ...STAFF_SIDE_ROLES] },
  ];

  // Subscription menu access (credentials area): menus hidden for this
  // member's audience — empty set = everything visible
  const audience = audienceForRole(data.user.role);
  const hiddenMenus = new Set(
    (audience && data.menuAccess?.hidden?.[audience]) ?? []
  );

  const nav = allNav
    .filter((item) => !item.roles || item.roles.includes(data.user!.role))
    .filter((item) => !item.menuKey || !hiddenMenus.has(item.menuKey))
    .map(({ roles: _roles, menuKey: _menuKey, ...item }) => item);

  // Staff logins the admin assigned as Student Identity maintainers jump
  // straight to the portal page from their member area.
  if (data.user.isIdentityManager) {
    nav.push({ href: "/portal/identity", label: t.portal.identityPage.title, icon: IconCard, group: t.navGroups.account });
  }

  return (
    <PanelShell
      navItems={nav}
      panelTitle={data.user.institution?.name ?? t.nav.memberPortal}
      userName={data.user.name}
      userEmail={data.user.username ?? data.user.email ?? ""}
      roleLabel={t.status[data.user.role as keyof typeof t.status] ?? data.user.role}
      accentLabel={data.user.institution?.name ?? undefined}
      logoUrl={data.user.institution?.logo ?? undefined}
    >
      {children}
    </PanelShell>
  );
}
