import useWebSocket from "react-use-websocket";
import React from "react";
import {useParams} from "react-router";
import {GHButton} from "../components/Button";
import useTitle from "../../utils/TitleHook";
import Card from "../components/Card";
import Hand from "../components/Hand";

interface GameState {
    PlayerName: string;
    Hand: string[];
    CurrentCard: string;
    CurrentPlayer: string;
    Players: string[];
}

const Room = () => {

    useTitle('Mau!');

    const {roomId} = useParams();

    const WS_URL = `ws://${process.env.REACT_APP_API_URL}/room/${roomId}`;

    const [gameState, setGameState] = React.useState<GameState>({PlayerName: '', Hand: [], CurrentCard: '', CurrentPlayer: '', Players: []});

    const websocket = useWebSocket(WS_URL, {
        onOpen: () => {
            console.log('WebSocket connection established.');
        },
        onMessage: (event) => {
            const data = JSON.parse(event.data);
            setGameState(data);
        }
    });

    const handleLeaveRoom = () => {
        window.location.href = '/';
    }

    const handleCardSend = (card: string) => {
        const formattedCard = JSON.stringify({CardType: card.split(' ')[0], CardValue: card.split(' ')[1]});
        websocket.sendMessage(formattedCard);
    }

    return (
        <div>
            <h1>Room {roomId}</h1>
            <GHButton onClick={handleLeaveRoom}>Leave Room</GHButton>
            {
                gameState.CurrentCard &&
                <Card cardString={gameState.CurrentCard}/>
            }
            <Hand hand={gameState.Hand} actionOnClick={handleCardSend}/>
            <ul>
                {
                    gameState.Players.map((player, index) => {
                        return <li key={index} style={{fontWeight: player === gameState.CurrentPlayer ? 'bold' : 'normal'}}>{player} {player === gameState.PlayerName && '(You)'}</li>
                    })
                }
            </ul>
        </div>
    )
}

export default Room;
