import { Suspense, lazy } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import AppLayout from "@/layouts/AppLayout";
import { useAuth } from "@/hooks/useAuth";
import { menuRoutes,extraRoutes } from "./routes";

const Login = lazy(() => import("@/pages/auth/login"));
const ResetPassword = lazy(() => import("@/pages/auth/reset-password"));
const MeetingPreview = lazy(() => import("@/pages/business/MeetingPreview"));

function RouteFallback() {
  let platformName = "iMeeting";
  try {
    const configStr = sessionStorage.getItem("platformConfig");
    if (configStr) {
      const config = JSON.parse(configStr);
      if (config.projectName) {
        platformName = config.projectName;
      }
    }
  } catch (e) {
    // ignore
  }

  return (
    <div className="ai-meeting-loader">
      <div className="ai-meeting-loader-backdrop" />
      <div className="ai-meeting-loader-content">
        <div className="ai-audio-core">
          <div className="ai-ring" />
          <div className="ai-ring" />
          <div className="ai-ring" />
          <div className="ai-core-glow" />
          <div className="ai-spectrum">
            <span className="ai-bar" />
            <span className="ai-bar" />
            <span className="ai-bar" />
            <span className="ai-bar" />
            <span className="ai-bar" />
          </div>
        </div>
        <div className="ai-meeting-text">
          <div className="ai-platform-name">{platformName}</div>
          <div className="ai-loading-status">A.I. ENGINE INITIALIZING</div>
        </div>
      </div>
    </div>
  );
}

function RequireAuth({ children }: { children: JSX.Element }) {
  const { isAuthed, profile } = useAuth();

  if (!isAuthed) {
    return <Navigate to="/login" replace />;
  }

  if (profile?.pwdResetRequired === 1) {
    return <Navigate to="/reset-password" replace />;
  }

  return children;
}

export default function AppRoutes() {
  return (
    <Suspense fallback={<RouteFallback />}>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/reset-password" element={<ResetPassword />} />
        <Route
          path="/meetings/:id/preview"
          element={<MeetingPreview />}
        />
        <Route
          path="/"
          element={
            <RequireAuth>
              <AppLayout />
            </RequireAuth>
          }
        >
          {menuRoutes.map((route) => (
            <Route key={route.path} index={route.path === "/"} path={route.path === "/" ? undefined : route.path.slice(1)} element={route.element} />
          ))}
          {extraRoutes && extraRoutes.map((route) => (
              <Route key={route.path} path={route.path.startsWith('/') ? route.path.slice(1) : route.path} element={route.element} />
          ))}
        </Route>
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </Suspense>
  );
}
