import * as React from 'react'
import PJCreationMenu from '@lastres/components/pj-creation-menu'
import PJListSelection from '@lastres/components/pj-list-selection'
import { fetchMyPjs } from '@lastres/pj'
import type { PJ } from '@lastres/pj'

export interface PJSelectionMenuProps {
    setSelectedPJ: (set: PJ | null) => void
    setUserWantsToCreatePJ: (set: boolean) => void
    userWantsToCreatePJ: boolean
    error: string | null
    setError: (set: string | null) => void
}

export default function PJSelectionMenu (props: PJSelectionMenuProps): JSX.Element {
    const [pjs, setPJs] = React.useState<PJ[] | null>(null)
    const createPJ = (): void => {
        props.setUserWantsToCreatePJ(true)
    }
    if (props.userWantsToCreatePJ) {
        return (
            <PJCreationMenu
                setSelectedPJ={props.setSelectedPJ}
                setUserWantsToCreatePJ={props.setUserWantsToCreatePJ}
                error={props.error}
                setError={props.setError}
                setPJs={setPJs}/>
        )
    }
    if (pjs === null) {
        fetchMyPjs(props.setError)
            .then((pjs) => { setPJs(pjs) })
            .catch((error) => { console.log(error) })
    }
    return (
        <div className="pj-selection-menu">
            <div className="pj-selection-menu-container">
                <h1>L3TDE</h1>
                <h2>Selecciona un Personaje</h2>
                <div className="pj-list">
                    <a onClick={createPJ} href="#">Crear un nuevo personaje</a>
                    <PJListSelection setSelectedPJ={props.setSelectedPJ} pjs={pjs}/>
                </div>
            </div>
        </div>
    )
}
