import { h, type FunctionComponent } from 'preact'
import { useState } from 'preact/hooks'
import { Router } from 'preact-router'

import CurrentUserContext from '../contexts/current_user.ts'
import { NotificationsProvider } from '../contexts/notifications.tsx'
import routes from '../routes.ts'

import Route from './route.tsx'

import CurrentUser from './current_user.tsx'
import Navigation from './navigation.tsx'
import Notifications from './notifications.tsx'
import NotFoundPage from './not_found_page.tsx'
import s from './app.module.scss'

const App: FunctionComponent<{ state: ANY }> = ({ state }) => {
  const [user, setUser] = useState(state.user)

  return (
    <NotificationsProvider defaultTimeout={15e3}>
      <CurrentUserContext.Provider value={{ user, setUser }}>
        <div className={s.base}>
          <a href='/admin' className={s.logo}>
            Carson Admin
          </a>

          <header className={s.header}>
            <CurrentUser className={s.currentUser} />
          </header>

          {user && (
            <aside className={s.aside}>
              <Navigation base='/admin' routes={routes} />
            </aside>
          )}

          <main className={s.main}>
            <Router>
              {routes
                ?.flatMap((route) => route.routes || route)
                .map(({ auth, component, path }) => (
                  <Route key={path} path={'/admin' + path} component={component} auth={auth} />
                ))}
              <NotFoundPage default />
            </Router>
          </main>
          <Notifications />
        </div>
      </CurrentUserContext.Provider>
    </NotificationsProvider>
  )
}

export default App
