import { BrowserRouter as Router, Route, Routes, Navigate } from "react-router-dom"
import Main from "./pages/Main"
import Users from "./pages/Users"
import Roles from "./pages/Roles"
import NotFound from "./pages/NotFound"
import DashboardLayout from "./layouts/DashboardLayout"
import MainLayout from "./layouts/MainLayout"
import SignIn from "./pages/auth/SignIn"
import ApiTest from "./pages/ApiTest"
import SignUp from "./pages/auth/SignUp"
import { initAuth, useAuthStore } from "./store/auth"
import { useEffect, useState } from "react"
import { Box, CircularProgress } from "@mui/material"
import Documents from "./pages/Documents"
import Reports from "./pages/Reports"
import Boilers from "./pages/Boilers"
import Servers from "./pages/Servers"

function App() {
  const auth = useAuthStore()
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    initAuth()
  }, [])

  // Once auth is there, set loading to false and render the app
  useEffect(() => {
    if (auth) {
      setIsLoading(false)
    }
  }, [auth])

  if (isLoading) {
    return (
      <CircularProgress />
    )
  } else {
    return (
      <Box sx={{
        width: "100%",
        height: "100vh"
      }}>
        <Router>
          <Routes>
            <Route element={<MainLayout />}>
              <Route path="/auth/signin" element={<SignIn />} />
              <Route path="/auth/signup" element={<SignUp />} />
            </Route>

            <Route element={auth.isAuthenticated ? <DashboardLayout /> : <Navigate to={"/auth/signin"} />}>
              <Route path="/" element={<Main />} />
              <Route path="/user" element={<Users />} />
              <Route path="/role" element={<Roles />} />
              <Route path="/documents" element={<Documents />} />
              <Route path="/reports" element={<Reports />} />
              <Route path="/servers" element={<Servers />} />
              <Route path="/boilers" element={<Boilers />} />
              <Route path="/api-test" element={<ApiTest />} />
              <Route path="*" element={<NotFound />} />
            </Route>
          </Routes>
        </Router>
      </Box>
    )
  }
}

export default App