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

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 = () => {
        const socket = websocket.getWebSocket();
        if (socket) socket.close();
        window.location.href = '/';
    }

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

    const handleDraw = () => {
        const formattedAction = JSON.stringify({
            Action: "DRAW",
            Data: ""
        });
        websocket.sendMessage(formattedAction);
    }

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

export default Room;
