import { BrowserRouter as Router, Route, Routes, Navigate } from "react-router-dom"
import NotFound from "./pages/NotFound"
import MainLayout from "./layouts/MainLayout"
import { initAuth, useAuthStore } from "./store/auth"
import { useEffect, useState } from "react"
import DashboardLayout from "./layouts/DashboardLayout"
import { Box, Loader } from "@mantine/core"
import { pages } from "./constants/app"

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 (
      <Loader />
    )
  } else {
    return (
      <Box w='100%' h='100vh'>
        <Router>
          <Routes>
            <Route element={<MainLayout />}>
              {pages.filter((page) => !page.dashboard).filter((page) => page.enabled).map((page, index) => (
                <Route key={`ml-${index}`} path={page.path} element={page.component} />
              ))}
            </Route>

            <Route element={auth.isAuthenticated ? <DashboardLayout></DashboardLayout> : <Navigate to={"/auth/signin"} />}>
              {pages.filter((page) => page.dashboard).filter((page) => page.enabled).map((page, index) => (
                <Route key={`dl-${index}`} path={page.path} element={page.component} />
              ))}
              <Route path="*" element={<NotFound />} />
            </Route>
          </Routes>
        </Router>
      </Box>
    )
  }
}

export default App