import { render } from 'preact'
import { useEffect, useState } from 'preact/hooks'
import { AdminPanel } from './pages/Admin.jsx'
import { ApiKeys } from './pages/ApiKeys.jsx'
import { Icon } from './components/Icon.jsx'
import { Login } from './pages/Login.jsx'
import { Store, useStore } from './context.jsx'
import { changeCase, useRouter, useUser } from './util.jsx'
import { Dashboard } from './pages/Dashboard.jsx'
import { showToast, Toasts } from './components/Toasts.jsx'
import { Sidebar } from './components/Sidebar.jsx'
import { MainContent } from './components/MainContent.jsx'

const App = () => {
    const [id, route, routeParams] = useRouter({
        index: {
            pattern: '/',
            name: 'Dashboard',
        },
        login: {
            pattern: '/login',
            name: 'Login',
        },
        admin: {
            pattern: '/admin',
            name: 'Admin',
        },
        apiKeys: {
            pattern: '/api-keys',
            name: 'API Keys',
        },
        buckets: {
            pattern: '/buckets',
            name: 'Buckets',
        },
        bucket: {
            pattern: '/buckets/:bucket',
            name: 'Bucket',
        },
    })

    if (id === 'unknown') {
        location.href = '/'
    }

    const user = useUser(user => {
        if (id !== 'login' && user !== 'admin') {
            location.href = '/login'
        }
        if (id === 'login' && user === 'admin') {
            location.href = '/'
        }
    })

    const [toasts, setToasts] = useState([])
    const [sidebarVisibile, setSidebarVisible] = useState(true)

    const [buckets, setBuckets] = useState([])
    useEffect(() => {
        fetch('/api/buckets')
            .then(res => res.json())
            .then(value => setBuckets(value))
    }, [])

    const context = {
        // Auth
        user,
        // Sidebar
        sidebarVisibile,
        setSidebarVisible,
        buckets,
        // Toasts
        toasts,
        setToasts,
        showToast: showToast(toasts, setToasts),
        // Routing
        route: {
            ...route,
            id,
            params: routeParams,
        },
    }

    return (
        <Store.Provider value={context}>
            <Sidebar />
            <MainContent />
            <Toasts />
        </Store.Provider>
    )
}

render(<App />, document.querySelector('main'))
