import { route } from 'preact-router'

import { useState } from 'preact/hooks'
import { prependBaseUrl } from '../api.js'
import { Header } from '../components/Header.jsx'

export const LoginPage = () => {
    const [username, setUsername] = useState('')

    const login = async () => {
        // @ts-ignore
        await fetch(prependBaseUrl(`/api/login`), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                id: username,
            }),
        })

        route(prependBaseUrl('/'))
    }

    return (
        <main class="page-login">
            <Header noLogin />
            <div class="subtitle">Accedi</div>
            <div class="form">
                <label for="login-username">Username</label>
                <input
                    id="login-username"
                    type="text"
                    value={username}
                    onInput={e => setUsername(e.target instanceof HTMLInputElement ? e.target.value : '')}
                    onKeyDown={e => e.key === 'Enter' && login()}
                />

                <div class="fill">
                    <button onClick={login}>Accedi</button>
                </div>
            </div>
        </main>
    )
}
