"use client";

import { useEffect, useMemo } 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 { PortalConfigContext } from "@/components/PortalConfig";
import { PageLoader } from "@/components/ui";
import { useApi } from "@/lib/client";
import {
  IconBell,
  IconBook,
  IconBox,
  IconBriefcase,
  IconCalendar,
  IconCard,
  IconClipboard,
  IconDollar,
  IconFile,
  IconHome,
  IconLayers,
  IconAward,
  IconLifeBuoy,
  IconMail,
  IconMessageCircle,
  IconSend,
  IconTrend,
  IconTruck,
  IconUser,
  IconUsers,
  IconWallet,
  IconShield,
} from "@/components/icons";

interface Me {
  user: {
    id: number;
    name: string;
    email: string;
    role: string;
    institution: { id: number; name: string; type: string; status: string; logo?: string | null } | null;
  } | null;
  /** subscription menu access — hidden sidebar menus per audience */
  menuAccess?: { hidden: { INSTITUTION: string[] } & Record<string, string[]> };
}

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  const { t, applyAcademicLabels } = useLang();
  const router = useRouter();
  const { data, loading, error } = useApi<Me>("/api/auth/me");

  const academicLabels = useMemo(
    () =>
      (data?.user?.institution as { academicLabels?: Record<string, string> | null } | null)
        ?.academicLabels ?? null,
    [data]
  );

  // Academic Terms Renaming: merge this institution's label overrides into
  // the dictionary so every page, header and dropdown uses them; cleared
  // again when leaving the portal shell (central/member stay with defaults).
  useEffect(() => {
    applyAcademicLabels(academicLabels);
    return () => applyAcademicLabels(null);
  }, [academicLabels, applyAcademicLabels]);


  // 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 allNav: {
    href: string;
    label: string;
    icon: React.ComponentType<{ className?: string }>;
    roles?: string[];
    module?: 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. menuKey marks the
    // items the credentials area can hide per subscription plan.
    { href: "/portal", label: t.common.dashboard, icon: centralNavIcons.dashboard, group: t.navGroups.general },
    { href: "/guide", label: t.guide.navLabel, icon: centralNavIcons.academic, external: true, group: t.navGroups.general },
    { href: "/portal/profile", label: t.portal.profile.title, icon: IconUser, group: t.navGroups.general },
    { href: "/portal/admissions", label: t.portal.admissionsPage.title, icon: IconClipboard, group: t.navGroups.admissions, menuKey: "admissions" },
    { href: "/portal/inquiries", label: t.portal.inquiriesPage.title, icon: centralNavIcons.academic,
      group: t.navGroups.admissions, roles: ["INSTITUTION_ADMIN"], menuKey: "inquiries" },
    { href: "/portal/students", label: t.portal.studentsPage.title, icon: IconUsers, group: t.navGroups.admissions, menuKey: "students" },
    { href: "/portal/identity", label: t.portal.identityPage.title, icon: IconCard,
      group: t.navGroups.admissions, roles: ["INSTITUTION_ADMIN", ...STAFF_SIDE_ROLES], menuKey: "identity" },
    { href: "/portal/control-panel", label: t.portal.controlPanelPage.title, icon: centralNavIcons.dashboard,
      group: t.navGroups.administration, roles: ["INSTITUTION_ADMIN"] },
    { href: "/portal/fees", label: t.portal.feesPage.title, icon: IconWallet, group: t.navGroups.finance, module: "fees", menuKey: "fees" },
    { href: "/portal/accounts", label: t.portal.accountsPage.title, icon: IconDollar, group: t.navGroups.finance, module: "accounts", menuKey: "accounts" },
    { href: "/portal/academic", label: t.common.academicInfo, icon: centralNavIcons.academic, group: t.navGroups.academics, menuKey: "academic" },
    { href: "/portal/promotions", label: t.portal.promotionsPage.title, icon: IconTrend, group: t.navGroups.academics, module: "promotions", menuKey: "promotions" },
    { href: "/portal/schedule", label: t.portal.schedulePage.title, icon: IconCalendar, group: t.navGroups.academics, module: "schedule", menuKey: "schedule" },
    { href: "/portal/exams", label: t.portal.examsPage.title, icon: IconFile, group: t.navGroups.academics, menuKey: "exams" },
    { href: "/portal/results", label: t.portal.resultsPage.title, icon: IconAward, group: t.navGroups.academics, menuKey: "results" },
    { href: "/portal/lesson-plans", label: t.portal.lessonPlanPage.title, icon: centralNavIcons.academic, group: t.navGroups.academics, module: "lessonPlans", menuKey: "lessonPlans" },
    { href: "/portal/omr", label: t.portal.omrPage.title, icon: IconLayers, group: t.navGroups.academics, module: "omr", menuKey: "omr" },
    // College & University (higher-education) modules — parallel to the
    // school-level flows, toggleable as one "campus" module
    { href: "/portal/campus/academic", label: t.portal.campusAcademicPage.title, icon: centralNavIcons.academic, group: t.navGroups.campus, module: "campus", menuKey: "campus" },
    { href: "/portal/campus/students", label: t.portal.campusStudentsPage.title, icon: IconUsers, module: "campus", menuKey: "campus" },
    { href: "/portal/campus/exams", label: t.portal.campusExamsPage.title, icon: IconFile, module: "campus", menuKey: "campus" },
    { href: "/portal/campus/results", label: t.portal.campusResultsPage.title, icon: IconAward, module: "campus", menuKey: "campus" },
    { href: "/portal/hr", label: t.portal.hrPage.title, icon: IconBriefcase, group: t.navGroups.hrCampus, module: "hr", menuKey: "hr" },
    { href: "/portal/library", label: t.portal.libraryPage.title, icon: IconBook, group: t.navGroups.hrCampus, module: "library", menuKey: "library" },
    { href: "/portal/hostel", label: t.portal.hostelPage.title, icon: IconHome, group: t.navGroups.hrCampus, module: "hostel", menuKey: "hostel" },
    { href: "/portal/inventory", label: t.portal.inventoryPage.title, icon: IconBox, group: t.navGroups.hrCampus, module: "inventory", menuKey: "inventory" },
    { href: "/portal/transport", label: t.portal.transportPage.title, icon: IconTruck, group: t.navGroups.hrCampus, module: "transport", menuKey: "transport" },
    { href: "/portal/notices", label: t.portal.noticesPage.title, icon: IconBell, group: t.navGroups.communication, module: "notices", menuKey: "notices" },
    { href: "/portal/events", label: t.portal.eventsPage.title, icon: IconCalendar, group: t.navGroups.communication, module: "events", menuKey: "events" },
    { href: "/portal/committees", label: t.portal.committeesPage.title, icon: IconUsers, group: t.navGroups.communication, module: "committees", menuKey: "committees" },
    { href: "/portal/complaints", label: t.portal.complaintsPage.title, icon: IconMessageCircle, group: t.navGroups.communication, module: "complaints", menuKey: "complaints" },
    { href: "/portal/support", label: t.portal.supportPage.title, icon: IconLifeBuoy, group: t.navGroups.communication, module: "support", menuKey: "support" },
    { href: "/portal/certificates", label: t.portal.certificatesPage.title, icon: IconAward, group: t.navGroups.communication, module: "certificates", menuKey: "certificates" },
    { href: "/portal/competitions", label: t.portal.competitionsPage.title, icon: IconTrend, group: t.navGroups.communication, module: "competitions", menuKey: "competitions" },
    { href: "/portal/messages", label: t.portal.messagesPage.title, icon: IconMail, group: t.navGroups.communication, module: "messages", menuKey: "messages" },
    { href: "/portal/communication", label: t.portal.communicationPage.title, icon: IconSend, group: t.navGroups.communication, module: "communication", menuKey: "communication" },
    { href: "/portal/verify", label: t.verifyPage.navLabel, icon: IconShield, group: t.navGroups.toolsBilling },
    { href: "/portal/packages", label: t.common.packages, icon: centralNavIcons.packages, group: t.navGroups.toolsBilling },
    { href: "/portal/billing", label: t.portal.billingPage.title, icon: centralNavIcons.payments, group: t.navGroups.toolsBilling },
  ];

  // Control Panel module toggles: null = every module on
  const enabledModules = (data.user.institution as { enabledModules?: string[] | null } | null)
    ?.enabledModules ?? null;
  // Subscription menu access (credentials area): menus hidden for the
  // institution audience — empty set = everything visible
  const hiddenMenus = new Set(data.menuAccess?.hidden?.INSTITUTION ?? []);
  // Campus (College & University) modules are exclusive to higher-education
  // institutions — other types never see the section or its pages
  const campusAllowed = data.user.institution?.type === "COLLEGE_AND_UNIVERSITY";
  const nav = allNav
    .filter((item) => {
      if (!data.user) return false;
      // admins get the full menu; other roles reach this shell only for the
      // pages their role is explicitly granted (Student Identity maintainers)
      if (data.user.role === "INSTITUTION_ADMIN") {
        return !item.roles || item.roles.includes(data.user.role);
      }
      return !!item.roles && item.roles.includes(data.user.role);
    })
    .filter((item) => campusAllowed || !item.href.startsWith("/portal/campus"))
    .filter((item) => !item.module || !enabledModules || enabledModules.includes(item.module))
    .filter((item) => !item.menuKey || !hiddenMenus.has(item.menuKey))
    .map(({ roles: _roles, module: _module, menuKey: _menuKey, ...item }) => item);

  return (
    <PortalConfigContext.Provider value={{ academicLabels: academicLabels ?? {}, enabledModules }}>
      <PanelShell
        navItems={nav}
        panelTitle={t.nav.institutionPortal}
        userName={data.user.name}
        userEmail={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>
    </PortalConfigContext.Provider>
  );
}
