import React, { useEffect } from "react";
import { Routes, Route, Navigate, useNavigate } from "react-router-dom";
import { Helmet, HelmetProvider, HtmlProps } from "react-helmet-async";
import { ToastContainer } from "react-toastify";
import { useTranslation } from "react-i18next";
import config from "./config.json";
import authentication from "./modules/frame/services/authenticationService";
import ForgotPassword from "./modules/frame/components/ForgotPassword";
import NotFound from "./modules/frame/components/NotFound";
import Logout from "./modules/frame/components/Logout";
import LoginForm from "./modules/frame/components/LoginForm";
import Mainframe from "./modules/frame/components/Mainframe";
import EmailUserAction from "./modules/frame/components/EmailUserAction";
import { HashNavigationProvider } from "./utils/HashNavigationContext";

import HomePage from "./modules/homepage/HomePage";
import Profile from "./modules/profile/Profile";
import EnvPage from "./modules/homepage/Env";
import Sequence from "./modules/manager/sequence/sequence";
import HOCSequenceDetails from "./modules/manager/sequence/SequenceDetails";
import CustomFields from "./modules/manager/customfields/customFields";
import HOCCustomFieldDetails from "./modules/manager/customfields/customFieldDetails";
import Forms from "./modules/manager/forms/Forms";
import HOCFormsDetails from "./modules/manager/forms/FormsDetails";
import HOCGlossaries from "./modules/manager/glossary/Glossary";
import HOCGlossariesDetails from "./modules/manager/glossary/GlossariesDetails";
import HOCAudit from "./modules/audit/audit";
import Domains from "./modules/manager/domains/Domains";
import DomainsDetails from "./modules/manager/domains/DomainsDetails";
import Users from "./modules/manager/users/users";
import UserDetails from "./modules/manager/users/UserDetails";
import RolesDetails from "./modules/manager/domains/components/RolesDetails";
import AddUserToRole from "./modules/manager/domains/components/AddUserToRole";
import LoginFrame from "./modules/frame/components/loginFrame";
import theme from "./utils/theme";
import Organisations from "./modules/manager/organisations/Organisations";
import HOCOrganisationsDetails from "./modules/manager/organisations/OrganisationsDetails";
import Sites from "./modules/manager/sites/Sites";
import SiteDetails from "./modules/manager/sites/SiteDetails";
import Specifications from "./modules/manager/specifications/Specifications";
import SpecificationsDetails from "./modules/manager/specifications/SpecificationsDetails";
import BlockedIPs from "./modules/blockedIPs/blockedIPs";
import ErrorLogs from "./modules/errorLogs/errorLogs";
import SsoManager from "./modules/manager/ssoManager/ssoManager";
import SsoProviderDetails from "./modules/manager/ssoManager/SsoProviderDetails";
import { Namespaces } from "./i18n/i18n";
import WorkflowTemplateManager from "./modules/manager/workflowTemplates/WorkflowTemplateManager";
import WorkflowTemplateDetails from "./modules/manager/workflowTemplates/WorkflowTemplateDetails";

function GetSecureRoutes() {
  const { t } = useTranslation(Namespaces.Common);

  return (
    <>
      <Route
        path="/audit/:auditId"
        element={
          <Mainframe title={t("AuditLogs")}>
            <HOCAudit />
          </Mainframe>
        }
      />
      <Route
        path="/audit"
        element={
          <Mainframe title={t("AuditLogs")}>
            <HOCAudit />
          </Mainframe>
        }
      />
      <Route
        path="/blockedIPs"
        element={
          <Mainframe title={t("BlockedIPAddresses")}>
            <BlockedIPs />
          </Mainframe>
        }
      />
      <Route
        path="/exceptionlogs"
        element={
          <Mainframe title={t("ExceptionLogs")}>
            <ErrorLogs />
          </Mainframe>
        }
      />

      <Route
        path="/specifications/:organisationId/:siteId/add"
        element={
          <Mainframe title={t("SpecificationManager")}>
            <SpecificationsDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/specifications/:organisationId/:siteId/:specificationId"
        element={
          <Mainframe title={t("SpecificationManager")}>
            <SpecificationsDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/specifications/:organisationId/:siteId"
        element={
          <Mainframe title={t("SpecificationManager")}>
            <Specifications />
          </Mainframe>
        }
      />

      <Route
        path="/site/:organisationId/add"
        element={
          <Mainframe title={t("SiteManager")}>
            <SiteDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/site/:organisationId/:siteId"
        element={
          <Mainframe title={t("SiteManager")}>
            <SiteDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/site/:organisationId"
        element={
          <Mainframe title={t("SiteManager")}>
            <Sites />
          </Mainframe>
        }
      />
      <Route path="/site/" element={<Navigate replace to="/404" />} />

      <Route
        path="/organisations"
        element={
          <Mainframe title={t("e-print")}>
            <Organisations />
          </Mainframe>
        }
      />
      <Route
        path="/organisations/add"
        element={
          <Mainframe title={t("e-print")}>
            <HOCOrganisationsDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/organisations/:organisationId"
        element={
          <Mainframe title={t("e-print")}>
            <HOCOrganisationsDetails editMode={true} />
          </Mainframe>
        }
      />

      <Route path="/glossaries/add/" element={<Navigate replace to="/404" />} />
      <Route
        path="/glossaries/add/:glossaryId"
        element={
          <Mainframe title={t("GlossaryManager")}>
            <HOCGlossariesDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/glossaries/edit/"
        element={<Navigate replace to="/404" />}
      />
      <Route
        path="/glossaries/edit/:glossaryId"
        element={
          <Mainframe title={t("GlossaryManager")}>
            <HOCGlossariesDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/glossaries"
        element={
          <Mainframe title={t("GlossaryManager")}>
            <HOCGlossaries />
          </Mainframe>
        }
      />
      <Route
        path="/glossaries/:glossaryId"
        element={
          <Mainframe title={t("GlossaryManager")}>
            <HOCGlossaries />
          </Mainframe>
        }
      />

      <Route
        path="/forms/add"
        element={
          <Mainframe title={t("FormTemplateManager")}>
            <HOCFormsDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/forms/edit/:formId"
        element={
          <Mainframe title={t("FormTemplateManager")}>
            <HOCFormsDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/forms"
        element={
          <Mainframe title={t("FormTemplateManager")}>
            <Forms />
          </Mainframe>
        }
      />

      <Route
        path="/customfields/add"
        element={
          <Mainframe title={t("CustomFieldManager")}>
            <HOCCustomFieldDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/customfields/edit/:customFieldId"
        element={
          <Mainframe title={t("CustomFieldManager")}>
            <HOCCustomFieldDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/customfields"
        element={
          <Mainframe title={t("CustomFieldManager")}>
            <CustomFields />
          </Mainframe>
        }
      />

      <Route
        path="/sequence/add"
        element={
          <Mainframe title={t("SequenceManager")}>
            <HOCSequenceDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/sequence/edit/:sequenceId"
        element={
          <Mainframe title={t("SequenceManager")}>
            <HOCSequenceDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/sequence"
        element={
          <Mainframe title={t("SequenceManager")}>
            <Sequence />
          </Mainframe>
        }
      />

      <Route
        path="/domains/add"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <DomainsDetails isEditMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/domains/edit/:domainId/addRole"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <RolesDetails isEditMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/domains/edit/:domainId/editRole/:roleId"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <RolesDetails isEditMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/domains/edit/:domainId/editRole/:roleId/addUserToRole"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <AddUserToRole isEditMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/domains/edit/:domainId"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <DomainsDetails isEditMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/domains"
        element={
          <Mainframe title={t("ClientDomainManager")}>
            <Domains />
          </Mainframe>
        }
      />

      <Route
        path="/users/add"
        element={
          <Mainframe title={t("UserManager")}>
            <UserDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/users/edit/:userId"
        element={
          <Mainframe title={t("UserManager")}>
            <UserDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/users"
        element={
          <Mainframe title={t("UserManager")}>
            <Users />
          </Mainframe>
        }
      />

      <Route
        path="/ssoManager"
        element={
          <Mainframe title={t("SsoManager")}>
            <SsoManager />
          </Mainframe>
        }
      />
      <Route
        path="/ssoManager/add"
        element={
          <Mainframe title={t("SsoManager")}>
            <SsoProviderDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/ssoManager/edit/:ssoProviderId"
        element={
          <Mainframe title={t("SsoManager")}>
            <SsoProviderDetails editMode={true} />
          </Mainframe>
        }
      />
      <Route
        path="/workflowTemplates/add"
        element={
          <Mainframe title={t("WorkflowTemplates")}>
            <WorkflowTemplateDetails editMode={false} />
          </Mainframe>
        }
      />
      <Route
        path="/workflowTemplates"
        element={
          <Mainframe title={t("WorkflowTemplates")}>
            <WorkflowTemplateManager />
          </Mainframe>
        }
      />
      <Route
        path="/profile"
        element={
          <Mainframe title={t("Account")}>
            <Profile />
          </Mainframe>
        }
      />
      <Route
        path="/logout"
        element={
          <Mainframe>
            <Logout />
          </Mainframe>
        }
      />
      <Route
        path="/"
        element={
          <Mainframe title={t("e-suite")}>
            <HomePage />
          </Mainframe>
        }
      />
    </>
  );
}

function App() {
  let navigate = useNavigate();

  useEffect(() => {
    const timer = setInterval(async () => {
      try {
        if (authentication.hasToken()) {
          await authentication.refreshToken();

          if (authentication.tokenExpired()) {
            navigate("/login");
            authentication.logout();
          }
        }
      } catch (e: any) {
        console.log(e);
      }
    }, 10 * 1000);
    return () => clearInterval(timer);
  });

  const isSignedIn = authentication.getCurrentUser() != null;

  const secureRoutes = isSignedIn ? (
    GetSecureRoutes()
  ) : (
    <Route path="/" element={<Navigate to="/login" />} />
  );

  var htmlAttributes: HtmlProps = {
    "data-bs-theme": theme.getPreferredTheme(),
  };

  window
    .matchMedia("(prefers-color-scheme: dark)")
    .addEventListener("change", () => {
      window.location.reload();
    });

  return (
    <HelmetProvider>
      <HashNavigationProvider>
        <Helmet htmlAttributes={htmlAttributes}>
          <title>{config.applicationName}</title>
        </Helmet>
        <main>
          <Routes>
            <Route path="/env" element={<EnvPage />} />
            <Route
              path="/login"
              element={
                <LoginFrame>
                  <LoginForm />
                </LoginFrame>
              }
            />
            <Route
              path="/forgot-password"
              element={
                <LoginFrame>
                  <ForgotPassword />
                </LoginFrame>
              }
            />
            <Route
              path="/404"
              element={
                <LoginFrame>
                  <NotFound />
                </LoginFrame>
              }
            />
            <Route
              path="/emailuseraction/:token"
              element={
                <LoginFrame>
                  <EmailUserAction />
                </LoginFrame>
              }
            />
            {secureRoutes}
            <Route path="*" element={<Navigate replace to="/404" />} />
          </Routes>
          <ToastContainer />
        </main>
      </HashNavigationProvider>
    </HelmetProvider>
  );
}

export default App;
