import { Navigate, Route, RouterProvider, createBrowserRouter, createRoutesFromElements, useLocation, useRouteLoaderData } from 'react-router-dom'
import PropTypes from 'prop-types'

import { UserProvider } from './store/user'
import { ajax } from './utils/fetch'

import Layout from './components/Layout'

import Index from './pages/Index'
import Login from './pages/Login'
import Register from './pages/Register'
import NoMatch from './pages/NoMatch'
import Engine from './pages/Engine'
import Quests from './pages/Quests'
import User from './pages/User'
import { useRole } from './utils/roles'
import EditQuest from './pages/admin/Quest'
import AdminQuest from './pages/admin/Quests'

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route
      path="/"
      id="root"
      element={<Layout />}
      loader={async () => ajax('/api/user').catch(x => { console.log(x); return null })}
    >
      <Route
        index
        element={<Index />}
      />
      <Route
        id="quests"
        path="/quests"
        element={<Auth><Quests /></Auth>}
        loader={() => ajax('/api/games').catch(x => { console.log(x); return null })}
      />
      <Route path="me" element={<User />} />
      <Route path="login" element={<Login />} />
      <Route path="register" element={<Register />} />
      <Route
        path="go/:gameId"
        element={<Auth><Engine /></Auth>}
        loader={({ params }) => ajax(`/api/engine/${params.gameId}`).catch(x => { console.log(x); return null })}
      />
       <Route
        path="/admin/quests/new"
        element={<Auth role="creator"><EditQuest /></Auth>}
        // loader={() => ajax(`/api/admin/games`)}
      />
       <Route
        path="/admin/quests/:gameId"
        element={<Auth role="creator"><EditQuest /></Auth>}
        loader={async ({ params }) => {
          const quest = await ajax(`/api/admin/games/${params.gameId}`)
          const files = await ajax(`/api/admin/file/${params.gameId}`)

          return { quest, files }
        }
        }
      />
       <Route
        path="/admin/quests"
        element={<Auth role="creator"><AdminQuest /></Auth>}
        loader={() => ajax('/api/admin/games')}
      />

      <Route path="*" element={<NoMatch />} />
    </Route>
  )
)
function App () {
  return (
    <RouterProvider router={router} />
  )
}

function Auth (props) {
  const baseUser = useRouteLoaderData('root')
  const { user } = UserProvider.useContainer()
  const { hasRole } = useRole()
  const location = useLocation()
  if (!user && !baseUser) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }
  if (props.role && !hasRole(props.role)) {
    return null
  }

  return props.children
}

Auth.propTypes = {
  children: PropTypes.any,
  role: PropTypes.string
}

export default App
