import React from "react";
import {GHButton} from "../components/Button";
import {Link} from "react-router-dom";
import useTitle from "../../utils/TitleHook";

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

const Home = () => {

    useTitle('Home');

    const [rooms, setRooms] = React.useState<string[]>([]);

    React.useEffect(() => {
        fetch(ROOM_URL)
            .then(r => r.json())
            .then(data => setRooms(data));
    }, []);

    const handleCreateRoom = () => {
        fetch(ROOM_URL, {
            method: 'POST',
        }).then(r => r.json()).then(data => {
            setRooms([...rooms, data]);
        });
    }

    return (
        <div>
            <GHButton onClick={handleCreateRoom}>Create Room</GHButton>
            <ul>
                {
                    rooms.map((room, index) => {
                        return <li key={index}><Link to={`room/${room}`}>{room}</Link></li>
                    })
                }
            </ul>
        </div>
    );
}

export default Home;
