import React, {useState, useEffect } from 'react';
import { useAtom } from 'jotai';
import HomePage from './components/pages/HomePage';
import LocationsPage from './components/pages/Locations/LocationsPage';
import RoomsPage from './components/pages/RoomsPage';
import LocationForm from './components/pages/Locations/NewLocationForm'
import NotFound from './components/pages/NotFound';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import { Loader, AppShell, MediaQuery, Header, Center, Title, Burger, useMantineTheme } from '@mantine/core';
// import { useDebouncedValue, useLocalStorageValue } from '@mantine/hooks';

import { backendAPI, defaultURLS } from './services/backend-api';

import { serverConfigAtom, notificationQueueAtom } from './state/state'

import { generateNotification } from './components/Utilities';


import SideBar from './components/SideBar';
// import AppHeader from './components/AppHeader';
import LocationDetailsPage from './components/pages/Locations/LocationDetailsPage';



function App() {
  // Main nav/sidebar appshell openend
  const [isLoading, setIsLoading] = useState(true)

  const [opened, setOpened] = useState(false);

  const [, setServerConfig] = useAtom(serverConfigAtom)
  const [, setNotificationQueue] = useAtom(notificationQueueAtom)

  const theme = useMantineTheme();

  
  // const navigate = useNavigate();



  useEffect(() => {
    // navigate("/")// Reset to homepage on new load anywhere in the app

    const fetchSettings = async () => {
      setIsLoading(true)
      try {
        const results = await backendAPI.get('/config')
        // console.log("FULL RESULTS: ", results.config.baseURL)
        results.data.baseURL = defaultURLS.baseURL
        console.log("CONFIG: ", results.data)
        setServerConfig(results.data)
        const notification = generateNotification('success', 'Config Fetched', 'Config fetched from backend')
        setNotificationQueue((currentQueue) => ([...currentQueue, notification]))
      } catch(err) {
        const notification = generateNotification('error', 'Failed to fetch config', `Failed to fetch config: ${err}`)
        setNotificationQueue((currentQueue) => ([...currentQueue, notification]))
      }
      setIsLoading(false)
    }

    fetchSettings();

  }, [setServerConfig, setNotificationQueue])


  return (
        <>
        {isLoading ? <Center><Loader variant="bars" /></Center> : 
        <Router>
          <AppShell
              navbarOffsetBreakpoint="sm" // navbarOffsetBreakpoint controls when navbar should no longer be offset with padding-left
              fixed       // fixed prop on AppShell will be automatically added to Header and Navbar
              navbar={<SideBar />}
              header={
                <Header height={70} p="md">
                <div style={{ display: 'flex', alignItems: 'center', height: '100%' }}>
                  <MediaQuery largerThan="sm" styles={{ display: 'none' }}>
                    <Burger
                      opened={opened}
                      onClick={() => setOpened((o) => !o)}
                      size="sm"
                      color={theme.colors.gray[6]}
                      mr="xl"
                    />
                  </MediaQuery>
                  <MediaQuery largerThan="sm" styles={{ display: 'none' }}>
                    <Title order={4}>goInventorize</Title>
                  </MediaQuery>
                  <MediaQuery smallerThan="sm" styles={{ display: 'none' }}>
                    <Title>goInventorize</Title>
                  </MediaQuery>
                </div>
              </Header>

              }
            >
              <Routes>
                <Route path='*' element={<NotFound />} />
                <Route index element={<HomePage />}/>
                <Route path="locations">
                  <Route index element={<LocationsPage />} />
                  <Route path=":id" element={<LocationDetailsPage />} />
                  <Route path="new" element={<LocationForm />}/>
                </Route>
                <Route path="rooms">
                  <Route index element={<RoomsPage />} />
                </Route>
              </Routes>
          </AppShell>
        </Router>
      }
      </>
  );
}

export default App;
