import { BrowserRouter as Router, Route, Routes, Navigate, redirect } 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 { CircularProgress } from "@mui/material"

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 (
      <>
        <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="/api-test" element={<ApiTest />} />
              <Route path="*" element={<NotFound />} />
            </Route>
          </Routes>
        </Router>
      </>
    )
  }
}

export default App