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() {
  return <div className="app-page__empty-state" style={{ minHeight: 320 }}>Loading...</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={
            <RequireAuth>
              <MeetingPreview />
            </RequireAuth>
          }
        />
        <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>
  );
}
