import { Suspense, lazy, useCallback, useEffect, useState } from "react";
import "./App.css";
import {
  ASSIGNMENT_ROUTE_MAP,
  assignmentsPageKey,
  EXECUTOR_SHELL_PAGE_KEYS,
} from "./assignmentRoutes.js";
import AppShell from "./components/common/AppShell.jsx";
import PageLoadingFallback from "./components/common/PageLoadingFallback.jsx";
import {
  canUserDownloadVerifierRiskReport,
  openUserAssessmentReport,
} from "./components/user/userAssessmentReport.js";
import {
  consumeTokenFromUrl,
  getStoredAuth,
  clearStoredAuth,
  redirectToHseLogin,
  getMasterDashboardUrl,
} from "hse-auth";
import { getAuthToken, getSatLoginUrl } from "./apiConfig.js";
import {
  isExecuterVerifierRole,
  normalizeRoleKey,
  sessionRoleFromLoginPayload,
} from "./authRoles.js";

const UserDashboard = lazy(() => import("./components/user/UserDashboard.jsx"));
const AdminDashboard = lazy(() => import("./components/admin/AdminDashboard.jsx"));
const AdminPendingActionsPage = lazy(() => import("./components/admin/AdminPendingActionsPage.jsx"));
const AdminAssignVideoPage = lazy(() => import("./components/admin/AdminAssignVideoPage.jsx"));
const AdminAssignedVideosPage = lazy(() => import("./components/admin/AdminAssignedVideosPage.jsx"));
const AdminViewVideoPage = lazy(() => import("./components/admin/AdminViewVideoPage.jsx"));
const AdminQuestionsPage = lazy(() => import("./components/admin/AdminQuestionsPage.jsx"));
const AdminSectionsPage = lazy(() => import("./components/admin/AdminSectionsPage.jsx"));
const AdminSectionDetailPage = lazy(() => import("./components/admin/AdminSectionDetailPage.jsx"));
const AdminFormsCompositionPage = lazy(() => import("./components/admin/AdminFormsCompositionPage.jsx"));
const AdminFormsListPage = lazy(() => import("./components/admin/AdminFormsListPage.jsx"));
const AdminFormDetailsPage = lazy(() => import("./components/admin/AdminFormDetailsPage.jsx"));
const UploadVideoPage = lazy(() => import("./components/common/UploadVideoPage.jsx"));
const UserMyVideosPage = lazy(() => import("./components/user/UserMyVideosPage.jsx"));
const UserRiskReductionReportPage = lazy(() => import("./components/user/UserRiskReductionReportPage.jsx"));
const AdminBrowseFormsPage = lazy(() => import("./components/admin/AdminBrowseFormsPage.jsx"));
const ExecutorDashboard = lazy(() => import("./components/executor/ExecutorDashboard.jsx"));
const ExecutorAssignedPage = lazy(() => import("./components/executor/ExecutorAssignedPage.jsx"));
const VerifierPage = lazy(() => import("./components/executor/VerifierPage.jsx"));
const ExecutorVideoPage = lazy(() => import("./components/executor/ExecutorVideoPage.jsx"));

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [activePage, setActivePage] = useState("dashboard");
  const [authRole, setAuthRole] = useState("");
  const [selectedVideo, setSelectedVideo] = useState(null);
  const [selectedOracSection, setSelectedOracSection] = useState(null);
  /** Which section admin page to highlight / return to after closing section detail. */
  const [sectionReturnPage, setSectionReturnPage] = useState(
    "admin-orac-section-list",
  );
  /** Form list / edit page to highlight when on the form editor; back target from form details. */
  const [formReturnPage, setFormReturnPage] = useState("admin-orac-form-list");
  const [formDetailInitialId, setFormDetailInitialId] = useState(null);
  const [userName, setUserName] = useState("");
  const [userEmail, setUserEmail] = useState("");
  const [assignmentsLink, setAssignmentsLink] = useState(null);
  const [userVideoFilters, setUserVideoFilters] = useState({
    status: "all",
    token: 0,
  });
  const [userRiskReportAssessment, setUserRiskReportAssessment] = useState(null);
  const [userReportReturnPage, setUserReportReturnPage] = useState("my-videos");

  const clearAssignmentsLink = useCallback(() => setAssignmentsLink(null), []);

  const handleExecutorPageChange = useCallback((key) => {
    setAssignmentsLink(null);
    setActivePage(key);
  }, []);

  const goToExecutorVideos = useCallback(() => {
    handleExecutorPageChange("executor-videos");
  }, [handleExecutorPageChange]);

  const goToExecutorDashboard = useCallback(() => {
    handleExecutorPageChange("dashboard");
  }, [handleExecutorPageChange]);

  /** Opens the verifier review queue (risk document / sign-off). */
  const goToReview = useCallback(() => {
    handleExecutorPageChange("verifier-videos");
  }, [handleExecutorPageChange]);

  const goToAdminAssignedVideosList = useCallback(() => {
    setSelectedVideo(null);
    setActivePage("assigned-videos");
  }, []);

  const handleOpenUserVideoCategory = useCallback((status) => {
    const nextStatus =
      typeof status === "string" && status.trim() ? status : "all";
    setUserVideoFilters({ status: nextStatus, token: Date.now() });
    setActivePage("my-videos");
  }, []);

  const handleUserReportDownload = useCallback(
    (row) => {
      if (canUserDownloadVerifierRiskReport(row)) {
        setUserReportReturnPage(activePage === "dashboard" ? "dashboard" : "my-videos");
        setUserRiskReportAssessment(row);
        setActivePage("user-risk-report");
      } else {
        openUserAssessmentReport(row);
      }
    },
    [activePage],
  );

  useEffect(() => {
    if (activePage !== "user-risk-report" || userRiskReportAssessment) {
      return;
    }
    setActivePage("dashboard");
  }, [activePage, userRiskReportAssessment]);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      await consumeTokenFromUrl();
      if (cancelled) return;

      const stored = getStoredAuth();
      if (!stored?.token) {
        redirectToHseLogin();
        return;
      }

      const authData = {
        token: stored.token,
        user: {
          user_id: stored.user?.userId ?? stored.user?.user_id,
          employee_name: stored.user?.employeeName ?? stored.user?.employee_name,
          email_id: stored.user?.email ?? stored.user?.email_id,
        },
      };

      let resolvedRole = sessionRoleFromLoginPayload(authData);
      if (!resolvedRole) {
        resolvedRole = normalizeRoleKey(stored.roles?.[0] || "user");
      }

      setAuthRole(resolvedRole);
      setUserName(authData.user?.employee_name || "");
      setUserEmail(authData.user?.email_id || "");
      setIsLoggedIn(true);
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!isLoggedIn) return;
    if (activePage === "master-dashboard") {
      window.location.href = getMasterDashboardUrl();
    }
  }, [activePage, isLoggedIn]);

  useEffect(() => {
    if (!isLoggedIn) return;
    if (!authRole) return;
    const r = normalizeRoleKey(authRole);
    const userPages = [
      "dashboard",
      "upload",
      "my-videos",
      "user-risk-report",
      "master-dashboard",
    ];
    const adminPages = [
      "master-dashboard",
      "dashboard",
      "admin-pending",
      "assigned-videos",
      "admin-orac-question-list",
      "admin-orac-question-add",
      "admin-orac-section-list",
      "admin-orac-section-add",
      "admin-orac-section-edit",
      "admin-orac-section-detail",
      "admin-orac-form-list",
      "admin-orac-form-add",
      "admin-orac-form-edit",
      "admin-orac-form-details",
      "admin-orac-form-browse",
      "assign-video",
      "view-video",
    ];

    if (isExecuterVerifierRole(authRole)) {
      if (activePage === "executor-assignments-other") {
        setActivePage("executor-assignments");
        return;
      }
      if (activePage === "verifier-assignments-other") {
        setActivePage("verifier-assignments");
        return;
      }
      if (
        !EXECUTOR_SHELL_PAGE_KEYS.has(activePage) &&
        activePage !== "master-dashboard"
      ) {
        setActivePage("dashboard");
      }
    } else if (r === "admin") {
      if (!adminPages.includes(activePage)) {
        setActivePage("dashboard");
      }
    } else {
      if (!userPages.includes(activePage)) {
        setActivePage("dashboard");
      }
    }
  }, [isLoggedIn, authRole, activePage]);

  useEffect(() => {
    if (activePage !== "admin-orac-section-detail") {
      setSelectedOracSection(null);
    }
  }, [activePage]);

  useEffect(() => {
    if (activePage !== "admin-orac-form-details") {
      setFormDetailInitialId(null);
    }
  }, [activePage]);

  useEffect(() => {
    if (activePage === "admin-orac-section-detail" && !selectedOracSection) {
      setActivePage("admin-orac-section-list");
    }
  }, [activePage, selectedOracSection]);

  useEffect(() => {
    if (!isLoggedIn) return;
    const main = document.querySelector(".app-shell-content-main");
    if (main) main.scrollTop = 0;
  }, [isLoggedIn, activePage]);

  const handleLogout = () => {
    clearStoredAuth();
    redirectToHseLogin();
  };

  if (isLoggedIn) {
    const normalizedRole = normalizeRoleKey(authRole);
    const isAdmin = normalizedRole === "admin";
    const isExecutor = isExecuterVerifierRole(authRole);
    const isUser = !isAdmin && !isExecutor;

    const masterDashNavItem = {
      key: "master-dashboard",
      label: "EHS Master Dashboard",
    };

    const navItems = isAdmin
      ? [
          masterDashNavItem,
          { key: "dashboard", label: "Dashboard" },
          { key: "admin-pending", label: "Videos to assign" },
          { key: "assigned-videos", label: "Assigned Videos" },
          {
            type: "group",
            key: "nav-admin-form-mgmt",
            label: "Form management",
            defaultOpen: true,
            items: [
              { key: "admin-orac-form-browse", label: "View Forms" },
              { key: "admin-orac-form-list", label: "Form list" },
              { key: "admin-orac-form-add", label: "Add form" },
              { key: "admin-orac-form-edit", label: "Edit form" },
            ],
          },
          {
            type: "group",
            key: "nav-admin-section-mgmt",
            label: "Section management",
            defaultOpen: false,
            items: [
              { key: "admin-orac-section-list", label: "Section list" },
              { key: "admin-orac-section-add", label: "Add section" },
              { key: "admin-orac-section-edit", label: "Edit section" },
            ],
          },
          {
            type: "group",
            key: "nav-admin-question-mgmt",
            label: "Question management",
            defaultOpen: false,
            items: [
              { key: "admin-orac-question-list", label: "Question list" },
              { key: "admin-orac-question-add", label: "Add question" },
            ],
          },
        ]
      : isExecutor
        ? [
            masterDashNavItem,
            { key: "dashboard", label: "Dashboard" },
            { key: "upload", label: "Upload Video" },
            {
              type: "group",
              key: "nav-exec-assign",
              label: "Executor assignments",
              defaultOpen: true,
              items: [
                { key: "executor-assignments", label: "All" },
                {
                  key: "executor-assignments-not-started",
                  label: "Not started",
                },
                {
                  key: "executor-assignments-verification-required",
                  label: "Submitted to Verifier",
                },
                {
                  key: "executor-assignments-returned",
                  label: "Returned by verifier",
                },
                { key: "executor-assignments-done", label: "Done" },
              ],
            },
            {
              type: "group",
              key: "nav-ver-assign",
              label: "Verifier assignments",
              defaultOpen: false,
              items: [
                { key: "verifier-assignments", label: "All" },
                {
                  key: "verifier-assignments-not-started",
                  label: "Not started",
                },
                {
                  key: "verifier-assignments-in-process",
                  label: "Resubmitted by executor",
                },
                {
                  key: "verifier-assignments-returned",
                  label: "Returned to executor",
                },
                { key: "verifier-assignments-done", label: "Done" },
              ],
            },
            { key: "executor-videos", label: "Executor videos" },
            { key: "verifier-videos", label: "Verifier review" },
          ]
        : [
            masterDashNavItem,
            { key: "dashboard", label: "Dashboard" },
            { key: "upload", label: "Upload Video" },
            { key: "my-videos", label: "My Videos" },
          ];

    const handleAssignVideo = (video) => {
      setSelectedVideo({ ...video, _returnPage: "admin-pending" });
      setActivePage("assign-video");
    };

    const handleViewVideo = (video) => {
      setSelectedVideo({ ...video, _returnPage: "assigned-videos" });
      setActivePage("view-video");
    };

    let pageContent = null;

    if (isAdmin) {
      if (activePage === "dashboard") {
        pageContent = (
          <AdminDashboard
            onOpenPendingActions={() => setActivePage("admin-pending")}
            onOpenAssignedVideos={() => setActivePage("assigned-videos")}
          />
        );
      } else if (activePage === "admin-pending") {
        pageContent = (
          <AdminPendingActionsPage
            onAssignVideo={(video) => handleAssignVideo(video)}
          />
        );
      } else if (activePage === "assigned-videos") {
        pageContent = (
          <AdminAssignedVideosPage
            onViewVideo={(video) => handleViewVideo(video)}
          />
        );
      } else if (
        activePage === "admin-orac-question-list" ||
        activePage === "admin-orac-question-add"
      ) {
        const qMode =
          activePage === "admin-orac-question-list" ? "list" : "add";
        pageContent = <AdminQuestionsPage mode={qMode} />;
      } else if (
        activePage === "admin-orac-section-detail" &&
        selectedOracSection
      ) {
        pageContent = (
          <AdminSectionDetailPage
            key={selectedOracSection.section_id}
            section={selectedOracSection}
            onBack={() => setActivePage(sectionReturnPage)}
          />
        );
      } else if (
        activePage === "admin-orac-section-list" ||
        activePage === "admin-orac-section-add" ||
        activePage === "admin-orac-section-edit"
      ) {
        const sectionMode =
          activePage === "admin-orac-section-list"
            ? "list"
            : activePage === "admin-orac-section-add"
              ? "add"
              : "edit";
        pageContent = (
          <AdminSectionsPage
            mode={sectionMode}
            onNavigateToSectionList={() =>
              setActivePage("admin-orac-section-list")
            }
            onOpenSection={(sec) => {
              setSectionReturnPage(
                activePage === "admin-orac-section-edit"
                  ? "admin-orac-section-edit"
                  : "admin-orac-section-list",
              );
              setSelectedOracSection(sec);
              setActivePage("admin-orac-section-detail");
            }}
          />
        );
      } else if (activePage === "admin-orac-form-add") {
        pageContent = (
          <AdminFormsCompositionPage
            onNavigateToFormList={() => setActivePage("admin-orac-form-list")}
          />
        );
      } else if (
        activePage === "admin-orac-form-list" ||
        activePage === "admin-orac-form-edit"
      ) {
        const formListMode =
          activePage === "admin-orac-form-edit" ? "edit" : "list";
        pageContent = (
          <AdminFormsListPage
            mode={formListMode}
            onBackToDashboard={() => setActivePage("dashboard")}
            onOpenForm={(formId) => {
              setFormReturnPage(
                activePage === "admin-orac-form-edit"
                  ? "admin-orac-form-edit"
                  : "admin-orac-form-list",
              );
              setFormDetailInitialId(formId);
              setActivePage("admin-orac-form-details");
            }}
          />
        );
      } else if (activePage === "admin-orac-form-details") {
        pageContent = (
          <AdminFormDetailsPage
            key={
              formDetailInitialId != null
                ? `form-${formDetailInitialId}`
                : "form-pick"
            }
            initialFormId={formDetailInitialId}
            onBack={() => setActivePage(formReturnPage)}
            onNavigateAfterFormDeleted={() => setActivePage(formReturnPage)}
          />
        );
      } else if (activePage === "admin-orac-form-browse") {
        pageContent = <AdminBrowseFormsPage />;
      } else if (activePage === "assign-video" && selectedVideo) {
        pageContent = (
          <AdminAssignVideoPage
            video={selectedVideo}
            onBack={() => setActivePage("admin-pending")}
            onAssignmentComplete={goToAdminAssignedVideosList}
          />
        );
      } else if (activePage === "view-video" && selectedVideo) {
        pageContent = (
          <AdminViewVideoPage
            video={selectedVideo}
            onBack={() => setActivePage("assigned-videos")}
          />
        );
      }
    } else if (isExecutor) {
      const assignmentPreset = ASSIGNMENT_ROUTE_MAP[activePage];
      if (assignmentPreset) {
        pageContent = (
          <ExecutorAssignedPage
            assignmentsLink={assignmentsLink}
            onAssignmentsLinkConsumed={clearAssignmentsLink}
            onNavigateExecutorVideos={goToExecutorVideos}
            onNavigateToReview={goToReview}
            onNavigateExecutorDashboard={goToExecutorDashboard}
            routePreset={assignmentPreset}
          />
        );
      } else if (activePage === "upload") {
        pageContent = <UploadVideoPage onNavigateToReview={goToReview} />;
      } else if (activePage === "executor-videos") {
        pageContent = (
          <ExecutorVideoPage
            onNavigateToReview={goToReview}
            onNavigateExecutorDashboard={goToExecutorDashboard}
          />
        );
      } else if (activePage === "verifier-videos") {
        pageContent = <VerifierPage onNavigateToReview={goToReview} />;
      } else {
        pageContent = (
          <ExecutorDashboard
            onNavigateAssignments={({ view, category }) => {
              setAssignmentsLink({ token: Date.now(), view, category });
              setActivePage(assignmentsPageKey(view, category));
            }}
          />
        );
      }
    } else if (isUser) {
      if (activePage === "user-risk-report" && userRiskReportAssessment) {
        pageContent = (
          <UserRiskReductionReportPage
            assessment={userRiskReportAssessment}
            onBack={() => {
              setUserRiskReportAssessment(null);
              setActivePage(userReportReturnPage);
            }}
          />
        );
      } else if (activePage === "my-videos") {
        pageContent = (
          <UserMyVideosPage
            initialStatusFilter={userVideoFilters}
            onNavigateUpload={() => setActivePage("upload")}
            onDownloadReport={handleUserReportDownload}
          />
        );
      } else if (activePage === "dashboard") {
        pageContent = (
          <UserDashboard
            onOpenCategory={handleOpenUserVideoCategory}
            onDownloadReport={handleUserReportDownload}
          />
        );
      } else if (activePage === "upload") {
        pageContent = (
          <UploadVideoPage
            onUploadSuccessNavigate={() => setActivePage("my-videos")}
          />
        );
      } else {
        pageContent = <UserDashboard />;
      }
    }

    const shellActivePage =
      activePage === "user-risk-report"
        ? userReportReturnPage
        : activePage === "admin-orac-section-detail"
          ? sectionReturnPage
          : activePage === "admin-orac-form-details"
            ? formReturnPage
            : activePage;

    return (
      <AppShell
        activePage={shellActivePage}
        onChangePage={isExecutor ? handleExecutorPageChange : setActivePage}
        onLogout={handleLogout}
        navItems={navItems}
        userName={userName}
        userEmail={userEmail}
        role={normalizedRole}
      >
        <Suspense
          key={
            activePage === "admin-orac-section-detail" && selectedOracSection
              ? `admin-orac-section-${selectedOracSection.section_id}`
              : activePage === "admin-orac-form-details" &&
                  formDetailInitialId != null
                ? `admin-orac-form-${formDetailInitialId}`
                : activePage
          }
          fallback={<PageLoadingFallback />}
        >
          <div className="page-content-enter">{pageContent}</div>
        </Suspense>
      </AppShell>
    );
  }

  return null;
}

export default App;
