import React, { lazy, useCallback, useEffect, useState } from "react";
import { useAuth } from "../../context/AuthContext.jsx";
import { PermitValidityProvider, usePermitValidity } from "../../context/PermitValidityContext.jsx";
import { PtwNavigationProvider } from "../../context/PtwNavigationContext.jsx";
import { ADMIN_NAV_SECTIONS, handleAdminNav } from "../../config/adminNav.jsx";
import PortalShell from "../../components/layout/PortalShell.jsx";
import HandoverNotificationBell from "../../components/notifications/HandoverNotificationBell.jsx";
import { LazyPage } from "../../components/common/PageTransition.jsx";
import { useHandoverNotifications } from "../../hooks/useHandoverNotifications.js";
import {
  DEFAULT_NAV,
  navParamsFromOptions,
  parseNavFromHash,
  writeNavHash
} from "../../utils/ptwNavUrl.js";

const AdminOverviewPage = lazy(() => import("./AdminOverviewPage.jsx"));
const AdminUsersAccessPage = lazy(() => import("./AdminUsersAccessPage.jsx"));
const AdminActivityLogPage = lazy(() => import("./AdminActivityLogPage.jsx"));
const AdminFormManagementPage = lazy(() => import("./AdminFormManagementPage.jsx"));
const AdminJobTypeManagementPage = lazy(() => import("./AdminJobTypeManagementPage.jsx"));
const AdminSectionManagementPage = lazy(() => import("./AdminSectionManagementPage.jsx"));
const AdminQuestionManagementPage = lazy(() => import("./AdminQuestionManagementPage.jsx"));
const AdminPermitsPage = lazy(() => import("./AdminPermitsPage.jsx"));
const AdminFormFillPage = lazy(() => import("./AdminFormFillPage.jsx"));
const AdminPermitLifecyclePage = lazy(() => import("./AdminPermitLifecyclePage.jsx"));
const AdminPermitPreviewPage = lazy(() => import("./AdminPermitPreviewPage.jsx"));
const AdminRaiseTicketPage = lazy(() => import("./AdminRaiseTicketPage.jsx"));
const AdminTicketListPage = lazy(() => import("./AdminTicketListPage.jsx"));
const AdminTicketLogsPage = lazy(() => import("./AdminTicketLogsPage.jsx"));

function readInitialNavState() {
  const { id, params } = parseNavFromHash();
  return {
    activeNav: id,
    ticketLogFilter: params.ticketId || ""
  };
}

function AdminAppContent({ activeNav, setActiveNav, ticketLogFilter, setTicketLogFilter, goBack }) {
  const { auth, logout } = useAuth();
  const { workflowView, clearWorkflowView } = usePermitValidity();
  const user = auth?.user;
  const initials =
    (user?.employee_name || "AD")
      .split(/\s+/)
      .map((w) => w[0])
      .join("")
      .slice(0, 2)
      .toUpperCase() || "AD";

  const onNavigate = useCallback((id, options = {}) => {
    if (options.ticketId != null) {
      setTicketLogFilter(String(options.ticketId));
    } else if (id !== "ticket-logs") {
      setTicketLogFilter("");
    }
    if (id !== "permit-handover" && id !== "permit-handback" && id !== "permit-audit") {
      clearWorkflowView();
    }

    const didNavigate = handleAdminNav(id, setActiveNav, options);
    if (didNavigate) {
      writeNavHash(id, navParamsFromOptions(options));
    }
  }, [clearWorkflowView, setActiveNav, setTicketLogFilter]);

  useEffect(() => {
    if (
      activeNav !== "permit-handover" &&
      activeNav !== "permit-handback" &&
      activeNav !== "permit-audit"
    ) {
      clearWorkflowView();
    }
  }, [activeNav, clearWorkflowView]);

  const lifecycleType =
    activeNav === "permit-handover"
      ? "handover"
      : activeNav === "permit-handback"
        ? "handback"
        : activeNav === "permit-audit"
          ? "audit"
          : workflowView?.type;

  const handoverNotifications = useHandoverNotifications({
    enabled: Boolean(auth?.token)
  });

  const notificationBell = (
    <HandoverNotificationBell
      unread={handoverNotifications.unread}
      loading={handoverNotifications.loading}
      onMarkRead={handoverNotifications.markRead}
      onMarkAllRead={handoverNotifications.markAllRead}
      onOpenPermit={(row) => {
        if (!row?.permit_id) return;
        onNavigate("permit-preview", { permitId: row.permit_id });
      }}
    />
  );

  const pageKey = lifecycleType ? `lifecycle-${lifecycleType}` : activeNav;

  return (
    <PtwNavigationProvider activeNav={activeNav} navigate={onNavigate} goBack={goBack}>
      <PortalShell
        activeNav={activeNav}
        onNavigate={onNavigate}
        userInitials={initials}
        userRole={user?.role_name || "Admin"}
        onLogout={logout}
        appTitle="PTW Admin"
        navSections={ADMIN_NAV_SECTIONS}
        topbarExtra={notificationBell}
      >
        <LazyPage pageKey={pageKey}>
          {lifecycleType ? (
            <AdminPermitLifecyclePage
              type={lifecycleType}
              onDone={() => onNavigate("fill-form")}
            />
          ) : activeNav === "overview" ? (
            <AdminOverviewPage onNavigate={onNavigate} />
          ) : activeNav === "users-access" ? (
            <AdminUsersAccessPage />
          ) : activeNav === "activity-log" ? (
            <AdminActivityLogPage />
          ) : activeNav === "form-management" ? (
            <AdminFormManagementPage />
          ) : activeNav === "job-type-management" ? (
            <AdminJobTypeManagementPage />
          ) : activeNav === "section-management" ? (
            <AdminSectionManagementPage />
          ) : activeNav === "question-management" ? (
            <AdminQuestionManagementPage />
          ) : activeNav === "permits-submissions" ? (
            <AdminPermitsPage onNavigate={onNavigate} />
          ) : activeNav === "permit-preview" ? (
            <AdminPermitPreviewPage onNavigate={onNavigate} />
          ) : activeNav === "fill-form" ? (
            <AdminFormFillPage />
          ) : activeNav === "raise-ticket" ? (
            <AdminRaiseTicketPage onNavigate={onNavigate} />
          ) : activeNav === "ticket-list" ? (
            <AdminTicketListPage onNavigate={onNavigate} />
          ) : activeNav === "ticket-logs" ? (
            <AdminTicketLogsPage initialTicketId={ticketLogFilter} />
          ) : null}
        </LazyPage>
      </PortalShell>
    </PtwNavigationProvider>
  );
}

export default function AdminApp() {
  const initialNav = readInitialNavState();
  const [activeNav, setActiveNav] = useState(initialNav.activeNav);
  const [ticketLogFilter, setTicketLogFilter] = useState(initialNav.ticketLogFilter);

  useEffect(() => {
    if (!window.location.hash.replace(/^#\/?/, "").trim()) {
      writeNavHash(DEFAULT_NAV, {}, { replace: true });
    }
  }, []);

  useEffect(() => {
    function syncFromHash() {
      const { id, params } = parseNavFromHash();
      setActiveNav(id);
      setTicketLogFilter(params.ticketId || "");
    }

    window.addEventListener("hashchange", syncFromHash);
    return () => window.removeEventListener("hashchange", syncFromHash);
  }, []);

  const goBack = useCallback(() => {
    if (window.history.length > 1) {
      window.history.back();
      return;
    }
    if (activeNav !== DEFAULT_NAV) {
      setActiveNav(DEFAULT_NAV);
      setTicketLogFilter("");
      writeNavHash(DEFAULT_NAV, {}, { replace: true });
    }
  }, [activeNav]);

  const onNavigateForValidity = useCallback((id) => {
    const didNavigate = handleAdminNav(id, setActiveNav);
    if (didNavigate) {
      writeNavHash(id, navParamsFromOptions());
    }
  }, []);

  return (
    <PermitValidityProvider onNavigate={onNavigateForValidity}>
      <AdminAppContent
        activeNav={activeNav}
        setActiveNav={setActiveNav}
        ticketLogFilter={ticketLogFilter}
        setTicketLogFilter={setTicketLogFilter}
        goBack={goBack}
      />
    </PermitValidityProvider>
  );
}
