import React, { lazy, useState } from "react";
import AssignmentNotificationBell from "../../components/user/AssignmentNotificationBell.jsx";
import { USER_NAV_SECTIONS, handleUserNav } from "../../config/userNav.jsx";
import { useAuth } from "../../context/AuthContext.jsx";
import { useAssignmentNotifications } from "../../hooks/useAssignmentNotifications.js";
import PortalShell from "../../components/layout/PortalShell.jsx";
import { LazyPage } from "../../components/common/PageTransition.jsx";
import { authUserId } from "../../utils/jwtPayload.js";

const AssignedSwisPage = lazy(() => import("./AssignedSwisPage.jsx"));
const AssignmentListPage = lazy(() => import("./AssignmentListPage.jsx"));
const DocumentFormPage = lazy(() => import("./DocumentFormPage.jsx"));
const MyLocationSwisPage = lazy(() => import("./MyLocationSwisPage.jsx"));
const MySwisPage = lazy(() => import("./MySwisPage.jsx"));
const SubmittedDocumentPage = lazy(() => import("./SubmittedDocumentPage.jsx"));
const UserHomePage = lazy(() => import("./UserHomePage.jsx"));

export default function UserApp() {
  const { auth, logout } = useAuth();
  const [activeNav, setActiveNav] = useState("user-home");
  /** @type {null | { filter?: string, statusFilter?: string | number }} */
  const [navContext, setNavContext] = useState(null);
  /** @type {null | { documentId: number, documentNumber: number, mode: 'form' | 'view' }} */
  const [activeDoc, setActiveDoc] = useState(null);

  const user = auth?.user;
  const userId = authUserId(auth);
  const notifications = useAssignmentNotifications(userId);

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

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

  const openForm = (documentId, documentNumber) =>
    setActiveDoc({ documentId, documentNumber, mode: "form" });

  const viewSubmission = (documentId, documentNumber) =>
    setActiveDoc({ documentId, documentNumber, mode: "view" });

  const docProps = {
    onOpenForm: openForm,
    onViewSubmission: viewSubmission,
  };

  const pageKey = activeDoc
    ? `doc-${activeDoc.mode}-${activeDoc.documentId}`
    : activeNav;

  return (
    <PortalShell
      activeNav={activeNav}
      onNavigate={onNavigate}
      userInitials={initials}
      userRole={user?.role_name || "User"}
      onLogout={logout}
      appTitle="SWI"
      navSections={USER_NAV_SECTIONS}
      topbarActions={
        <AssignmentNotificationBell
          unread={notifications.unread}
          onMarkRead={notifications.markRead}
          onMarkAllRead={notifications.markAllRead}
          onOpenAssignment={(documentId, documentNumber, row) => {
            notifications.markRead(row);
            openForm(documentId, documentNumber);
          }}
          onViewAll={() => onNavigate("assigned-swis")}
        />
      }
    >
      <div
        className={
          activeDoc
            ? "portal-page portal-page--document-full"
            : "portal-page"
        }
      >
        <LazyPage pageKey={pageKey}>
          {activeDoc?.mode === "form" ? (
            <DocumentFormPage
              documentId={activeDoc.documentId}
              documentNumber={activeDoc.documentNumber}
              onBack={() => setActiveDoc(null)}
            />
          ) : activeDoc?.mode === "view" ? (
            <SubmittedDocumentPage
              documentId={activeDoc.documentId}
              documentNumber={activeDoc.documentNumber}
              onBack={() => setActiveDoc(null)}
            />
          ) : activeNav === "user-home" ? (
            <UserHomePage onNavigate={onNavigate} {...docProps} />
          ) : activeNav === "assigned-swis" ? (
            <AssignedSwisPage
              assignments={notifications.assignments}
              loading={notifications.loading}
              onRefresh={notifications.refresh}
              isUnread={notifications.isUnread}
              onMarkAllRead={notifications.markAllRead}
              onMarkRead={notifications.markRead}
              initialFilter={navContext?.filter}
              {...docProps}
            />
          ) : activeNav === "my-swis" ? (
            <MySwisPage
              initialStatusFilter={navContext?.statusFilter}
              {...docProps}
            />
          ) : activeNav === "my-location-swis" ? (
            <MyLocationSwisPage {...docProps} />
          ) : activeNav === "assignment-list" ? (
            <AssignmentListPage {...docProps} />
          ) : null}
        </LazyPage>
      </div>
    </PortalShell>
  );
}
