import React, { lazy, useState } from "react";
import { useAuth } from "../../context/AuthContext.jsx";
import { handleAdminNav, ADMIN_NAV_SECTIONS } from "../../config/adminNav.jsx";
import PortalShell from "../../components/layout/PortalShell.jsx";
import { LazyPage } from "../../components/common/PageTransition.jsx";

const AdminOverviewPage = lazy(() => import("./AdminOverviewPage.jsx"));
const CreateDocumentPage = lazy(() => import("./CreateDocumentPage.jsx"));
const AdminDocumentsPage = lazy(() => import("./AdminDocumentsPage.jsx"));
const AssignDocumentPage = lazy(() => import("./AssignDocumentPage.jsx"));
const AdminTicketsPage = lazy(() => import("./AdminTicketsPage.jsx"));
const AdminTicketLogsPage = lazy(() => import("./AdminTicketLogsPage.jsx"));
const AdminUsersPage = lazy(() => import("./AdminUsersPage.jsx"));
const AdminActivityPage = lazy(() => import("./AdminActivityPage.jsx"));
const AdminAuditsPage = lazy(() => import("./AdminAuditsPage.jsx"));

export default function AdminApp() {
  const { auth, logout } = useAuth();
  const [activeNav, setActiveNav] = useState("admin-overview");
  /** @type {null | { documentId?: number | string, documentNumber?: number | string }} */
  const [navContext, setNavContext] = useState(null);

  const user = auth?.user;
  const initials =
    (user?.employee_name || "AD")
      .split(/\s+/)
      .map((w) => w[0])
      .join("")
      .slice(0, 2)
      .toUpperCase() || "AD";

  const onNavigate = (id, context) => {
    setNavContext(context ?? null);
    handleAdminNav(id, setActiveNav);
  };

  return (
    <PortalShell
      activeNav={activeNav}
      onNavigate={onNavigate}
      userInitials={initials}
      userRole={user?.role_name || "Admin"}
      onLogout={logout}
      appTitle="SWI Admin"
      navSections={ADMIN_NAV_SECTIONS}
    >
      <div className="portal-page">
        <LazyPage pageKey={activeNav}>
          {activeNav === "admin-overview" ? (
            <AdminOverviewPage onNavigate={onNavigate} />
          ) : activeNav === "create-document" ? (
            <CreateDocumentPage onNavigate={onNavigate} />
          ) : activeNav === "my-documents" ? (
            <AdminDocumentsPage
              highlightDocumentId={navContext?.documentId}
              highlightDocumentNumber={navContext?.documentNumber}
            />
          ) : activeNav === "assign-document" ? (
            <AssignDocumentPage />
          ) : activeNav === "tickets" ? (
            <AdminTicketsPage />
          ) : activeNav === "ticket-logs" ? (
            <AdminTicketLogsPage onNavigate={onNavigate} />
          ) : activeNav === "users" ? (
            <AdminUsersPage />
          ) : activeNav === "activity-log" ? (
            <AdminActivityPage />
          ) : activeNav === "audits" ? (
            <AdminAuditsPage />
          ) : null}
        </LazyPage>
      </div>
    </PortalShell>
  );
}
