import * as React from 'react'

import { PJ } from '@lastres/pj'

import LoginPage from '@lastres/components/login-page'
import Game from '@lastres/components/game'
import { checkLogin } from '@lastres/login'
import RegistrationPage from '@lastres/components/registration-page'
// import Game from '@lastres/components/game'

export default function Page (): JSX.Element {
    const [isLoggedIn, setIsLoggedIn] = React.useState<boolean>(false)
    const [userWantsToCreatePJ, setUserWantsToCreatePJ] = React.useState<boolean>(false)
    const [isAskingForRegistration, setIsAskingForRegistration] = React.useState<boolean>(false)
    const [error, setError] = React.useState<string | null>(null)
    const [selectedPJ, setSelectedPJ] = React.useState<PJ | null>(null)
    checkLogin(setError, setIsLoggedIn)
    if (!isLoggedIn) {
        return notLoggedRender(setIsLoggedIn, isAskingForRegistration, setIsAskingForRegistration, error, setError)
    }
    return (
        <Game selectedPJ={selectedPJ}
            setSelectedPJ={setSelectedPJ}
            userWantsToCreatePJ={userWantsToCreatePJ}
            setUserWantsToCreatePJ={setUserWantsToCreatePJ}
            error={error}
            setError={setError}/>
    )
}

function notLoggedRender (setIsLoggedIn: (a: boolean) => void,
    isAskingForRegistration: boolean,
    setIsAskingForRegistration: (a: boolean) => void,
    error: string | null,
    setError: (a: string | null) => void): JSX.Element {
    if (isAskingForRegistration) {
        return (
            <>
                <RegistrationPage setIsLoggedIn={setIsLoggedIn}
                    setIsAskingForRegistration={setIsAskingForRegistration}
                    error={error}
                    setError={setError}/>
            </>
        )
    }
    return (
        <>
            <LoginPage setIsLoggedIn={setIsLoggedIn}
                error={error}
                setError={setError}
                setIsAskingForRegistration={setIsAskingForRegistration}/>
        </>
    )
}
