import { BrowserRouter as Router, Route, Routes } from "react-router-dom"
//import { 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 { pages } from "./constants/app"
import { FluentProvider, Spinner, webDarkTheme, webLightTheme } from "@fluentui/react-components"
import { setColorScheme, useAppStore } from "./store/app"

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

  useEffect(() => {
    const localColorScheme = localStorage.getItem('colorScheme');

    if (localColorScheme === 'light') {
      setColorScheme('light')
    } else if (localColorScheme === 'dark') {
      setColorScheme('dark')
    } else if (localColorScheme === 'auto') {
      setColorScheme('auto')
    }

    initAuth()
  }, [])

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

  if (isLoading) {
    return (
      <Spinner />
    )
  } else {
    return (
      <FluentProvider theme={colorScheme === 'light' ? webLightTheme : webDarkTheme}>
        <div style={{
          width: '100%',
          height: '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 || pages.find(page => page.path === '/auth/signin')?.enabled === false ? <DashboardLayout></DashboardLayout> : <Navigate to={"/auth/signin"} />}> */}
              <Route element={<DashboardLayout></DashboardLayout>}>
                {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>
        </div>
      </FluentProvider>
    )
  }
}

export default App