import Router from 'preact-router'
import { route } from 'preact-router'
import { useContext, useEffect } from 'preact/hooks'
import { prependBaseUrl } from './api'
import { ServerContext } from './hooks'
import { AdminPage } from './pages/Admin'

import { HomePage } from './pages/Home'
import { LoginPage } from './pages/Login'
import { ProblemPage } from './pages/Problem'
import { ProfilePage } from './pages/Profile'

const Redirect = ({ to }: { to: string }) => {
    useEffect(() => {
        route(prependBaseUrl(to), true)
    }, [])

    return (
        <>
            Redirecting to <pre>{to}</pre>...
        </>
    )
}

export const App = ({ url }: { url?: string }) => {
    // during server side rendering don't prepend the BASE_URL
    const pbu = useContext(ServerContext) ? (s: string) => s : prependBaseUrl

    console.log(`URL "${url}"`)

    return (
        <Router url={url}>
            <HomePage
                // @ts-ignore
                path={pbu('/')}
            />
            <LoginPage
                // @ts-ignore
                path={pbu('/login')}
            />
            <ProfilePage
                // @ts-ignore
                path={pbu('/profile')}
            />
            <ProblemPage
                // @ts-ignore
                path={pbu('/problem/:id')}
            />
            <AdminPage
                // @ts-ignore
                path={pbu('/admin')}
            />
            <Redirect
                // @ts-ignore
                default
                to="/"
            />
        </Router>
    )
}
