import React from "react";
import useTitle from "../../utils/hooks/TitleHook";
import Card from "../components/Card";
import {useNavigate} from "react-router";
import {NoButton} from "../components/Button";

const ROOM_URL = `${process.env.REACT_APP_API_URL}/room`;

const MainLobby = () => {

    useTitle('Mau-Mau Lobby');

    const navigateTo = useNavigate();
    const playerName = localStorage.getItem('playerName') ?? "";

    const handleCreateRoom = () => {
        fetch(ROOM_URL, {
            method: 'POST',
        }).then(res => res.json()).then(room => {
            navigateTo(`/room/${room}`);
        });
    }

    const changePlayerName = (name: string) => {
        if (!name) return;
        localStorage.setItem('playerName', name);
    }

    return (
        <div className={"main-lobby"}>
            <h1 className={"main-lobby__title mau"}>Mau-Mau</h1>
            <div className={"main-lobby__name mau"}>
                <label htmlFor={"name-input"}>Enter your name</label>
                <input id={"name-input"} type="text" placeholder="Enter your name"
                       defaultValue={playerName} onBlur={(e) => changePlayerName(e.target.value)}/>
            </div>
            <div className={"main-lobby__container"}>
                <NoButton className={"main-lobby__container-button"} onClick={handleCreateRoom}>
                    <h2 className={"mau"}>Host Game</h2>
                    <Card cardString={'SPADES ACE'} isClickable/>
                </NoButton>
                <NoButton className={"main-lobby__container-button"} onClick={() => navigateTo('/rooms')}>
                    <h2 className={"mau"}>Join Game</h2>
                    <Card cardString={'SPADES ACE'} isHidden isClickable/>
                </NoButton>
            </div>
        </div>
    );
}

export default MainLobby;
