import * as Sentry from "@sentry/react";
import { FloatButton, Layout, Spin } from "antd";
import { Suspense, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Navigate, Route, Routes, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import BreadCrumbs from "../../components/breadcrumbs/breadcrumbs.component.jsx";
import ConflictComponent from "../../components/conflict/conflict.component.jsx";
import ErrorBoundary from "../../components/error-boundary/error-boundary.component.jsx";
import GlobalFooter from "../../components/global-footer/global-footer.component.jsx";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component.jsx";
import ShopSubStatusComponent from "../../components/shop-sub-status/shop-sub-status.component.jsx";
import UpdateAlert from "../../components/update-alert/update-alert.component.jsx";
import { selectBodyshop, selectInstanceConflict } from "../../redux/user/user.selectors.js";
import InstanceRenderManager from "../../utils/instanceRenderMgr.js";
import useAlertsNotifications from "../../hooks/useAlertsNotifications.jsx";
import { lazyDev } from "../../utils/lazyWithPreload.jsx";

const SimplifiedPartsJobsPage = lazyDev(() => import("../simplified-parts-jobs/simplified-parts-jobs.page.jsx"));
const SimplifiedPartsJobsDetailPage = lazyDev(
  () => import("../simplified-parts-jobs-detail/simplified-parts-jobs-detail.container.jsx")
);
const PartsSettingsPage = lazyDev(() => import("../parts-settings/parts-settings.page.component.jsx"));
const ShopVendorPageContainer = lazyDev(() => import("../shop-vendor/shop-vendor.page.container.jsx"));
const EmailOverlayContainer = lazyDev(() => import("../../components/email-overlay/email-overlay.container.jsx"));
const ReportCenterModal = lazyDev(() => import("../../components/report-center-modal/report-center-modal.container.jsx"));
const PrintCenterModalContainer = lazyDev(
  () => import("../../components/print-center-modal/print-center-modal.container")
);
const VehiclesContainer = lazyDev(() => import("../vehicles/vehicles.page.container.jsx"));
const VehiclesDetailContainer = lazyDev(() => import("../vehicles-detail/vehicles-detail.page.container.jsx"));
const { Content } = Layout;

// Redirector to strip '/parts/jobs' from path for non-detail routes
function JobsStripRedirect() {
  const location = useLocation();
  const { pathname, search, hash } = location;
  const target = pathname.replace("/parts/jobs", "/parts") + (search || "") + (hash || "");
  return <Navigate to={target} replace />;
}

const mapStateToProps = createStructuredSelector({
  conflict: selectInstanceConflict,
  bodyshop: selectBodyshop
});

export function SimplifiedPartsPage({ conflict, bodyshop }) {
  const { t } = useTranslation();

  // Centralized alerts handling (fetch + dedupe + notifications)
  useAlertsNotifications();

  useEffect(() => {
    document.title = InstanceRenderManager({
      imex: t("titles.imexonline"),
      rome: t("titles.romeonline")
    });
  }, [t]);

  const AppRouteTable = (
    <Suspense
      fallback={
        <LoadingSpinner
          message={t("general.labels.loadingapp", {
            app: InstanceRenderManager({
              imex: "$t(titles.imexonline)",
              rome: "$t(titles.romeonline)"
            })
          })}
        />
      }
    >
      <BreadCrumbs />
      <ReportCenterModal />
      <EmailOverlayContainer />
      <PrintCenterModalContainer />
      <Routes>
        {/* Redirect legacy or relative routes that include '/jobs' segment */}
        <Route path="jobs" element={<JobsStripRedirect />} />
        <Route path="jobs/*" element={<JobsStripRedirect />} />

        <Route
          path="/"
          element={
            <Suspense fallback={<Spin />}>
              <SimplifiedPartsJobsPage />
            </Suspense>
          }
        />
        <Route
          path="/jobs/:jobId"
          element={
            <Suspense fallback={<Spin />}>
              <SimplifiedPartsJobsDetailPage />
            </Suspense>
          }
        />
        <Route
          path="/vehicles"
          element={
            <Suspense fallback={<Spin />}>
              <VehiclesContainer />
            </Suspense>
          }
        />
        <Route
          path="/vehicles/:vehId"
          element={
            <Suspense fallback={<Spin />}>
              <VehiclesDetailContainer />
            </Suspense>
          }
        />
        <Route
          path="/shop/vendors"
          element={
            <Suspense fallback={<Spin />}>
              <ShopVendorPageContainer />
            </Suspense>
          }
        />
        <Route
          path="/settings"
          element={
            <Suspense fallback={<Spin />}>
              <PartsSettingsPage />
            </Suspense>
          }
        />
      </Routes>
    </Suspense>
  );

  let PageContent;

  if (conflict) PageContent = <ConflictComponent />;
  else if (bodyshop && bodyshop.sub_status !== "active") PageContent = <ShopSubStatusComponent />;
  else PageContent = AppRouteTable;

  return (
    <Layout style={{ minHeight: "100vh" }} className="layout-container">
      <UpdateAlert />
      <Content className="content-container">
        <Sentry.ErrorBoundary fallback={<ErrorBoundary />} showDialog>
          {PageContent}
        </Sentry.ErrorBoundary>
        <FloatButton.BackTop style={{ right: 100, bottom: 25 }} />
      </Content>
      <GlobalFooter />
    </Layout>
  );
}

export default connect(mapStateToProps)(SimplifiedPartsPage);
