import React, {MouseEvent, useState} from 'react';
import {Input, Button, Card, Col, InputNumber, Row, Space, Divider} from "antd"
import { red } from '@ant-design/colors';

import connection, {useIsConnected, useRoom} from "../lib/Connection";

import "../css/lobby.sass";
import beer from "../img/beer.png"

const Lobby = (props: any) => {
    const [seekTime, setSeekTime] = useState(0);
    const [selectedRoomId, setSelectedRoomId] = useState(1);

    const [joiningLobby, setJoiningLobby] = useState(false);
    const [joinLobbyError, setJoinLobbyError] = useState(false);

    const isConnected = useIsConnected();
    const room = useRoom();

    let isLeader = room?.isLeader || false;
    let userCount = room?.userCount || 0;

    function handleRequestStartClicked(e: MouseEvent) {
        e.preventDefault();

        connection.requestStart();
    }

    function handleJoin(e: MouseEvent) {
        // connection.requestStart();
    }

    function applyRoomId(v: number) {
        connection.requestJoin(v).then(v => {
            setJoiningLobby(false);
            setJoinLobbyError(!v);
        })
        setJoiningLobby(true)
    }

    function joinRandomLobby() {
        connection.requestJoinRandom()
        setJoinLobbyError(false);
    }

    // const {socket} = useSocket("welcome", async (obj: any) => {
    //     if (lobbyQueryId) {
    //         // lobbyId is already defined, this means we have a queryparam set.
    //         await onChangeLobbyInput(lobbyQueryId);
    //         return;
    //     }
    //     console.log("Got welcome", lobbyQueryId);
    //
    //     setLobbyId(obj.room.name);
    //     setIsLeader(socket.id === obj.room.leaderId);
    //     setUserCount(obj.room.users?.length || 0);
    // });

    // const socketRef = useRef<SocketIOClient.Socket>(socket);

    async function onChangeRoomInput(i: any) {
        // setLobbyId(i);
        // const result: any = await emit(connection.socket, 'join_room', i);
        // setIsLeader(connection.socket.id === result.room.leaderId);
        // setUserCount(result.room.users?.length || 0);
        // connection.requestJoin(i);
    }

    // useEffect(() => {
    //     async function wrapper() {
    //         const result: any = await emit(connection.current, 'room_info');
    //         setIsLeader(connection.current.id === result.room.leaderId);
    //         setUserCount(result.room.users?.length || 0);
    //     }
    //
    //     wrapper();
    // }, []);

    return (
        <div className="lobby">
            <Row>
                <Col className="centurion-title" span={24}>
                    <div className="beer-flipped">
                        <img src={beer} className={`beer ${isConnected ? 'connected' : 'connecting'}`} alt="beer"/>
                    </div>
                    <span className="text">Centurion!</span>
                    <img src={beer} className={`beer ${isConnected ? 'connected' : 'connecting'}`} alt="beer"/>
                </Col>
            </Row>
            <Row>
                <Col className="hints" span={24}>
                    <div>Honderd minuten...</div>
                    <div>Honderd shots...</div>
                    <div>Kun jij het aan?</div>
                </Col>
            </Row>
            <br/>

            {!isConnected &&
            <Row justify="center">
                <Col className="lobby-connecting">
                    <h2>Verbinden...</h2>
                </Col>
            </Row>
            }

            {isConnected &&
            <Row justify="center">
                <Col xs={12} sm={10} md={10} xl={6}>
                    <Card>
                        <h3>Huidige lobby: <b>{room?.id || 'Geen lobby'}</b></h3>

                        <Row>
                            <Col>
                                {userCount === 1 ?
                                    <p>Er is één gebruiker aanwezig.</p>
                                    :
                                    <p>Er zijn {userCount} gebruikers aanwezig.</p>
                                }

                                <p>{isLeader ? 'Jij bent de baas van deze lobby.' : 'Wachten tot de baas de mix start.'}</p>

                            </Col>
                        </Row>

                        <Row>
                            <Col>
                                {isLeader &&
                                <span>Start de mix op
                                <Input
                                    type="number"
                                    min={0}
                                    max={60000}
                                    suffix="sec"
                                    value={seekTime}
                                    onChange={v => setSeekTime(parseInt(v.target.value) || 0)}/>
                                </span>
                                }
                            </Col>
                        </Row>

                        {isLeader ?
                            <Button
                                block
                                type="primary"
                                onClick={handleRequestStartClicked}>Start</Button>
                            :
                            <Button
                                block
                                type="primary"
                                disabled={!room}
                                onClick={handleJoin}>Join</Button>
                        }

                        <Divider/>

                        <Row justify="center">
                            <Col>
                                <InputNumber
                                    style={{'width': 'calc(100% - 150px)'}}
                                    min={1}
                                    max={100000}
                                    value={selectedRoomId || room?.id || 0}
                                    onChange={(v) => setSelectedRoomId(v || 0)}/>

                                <Button
                                    style={{'width': '150px'}}
                                    type="primary"
                                    loading={joiningLobby}
                                    onClick={() => {
                                        applyRoomId(selectedRoomId)
                                    }}>Verander van lobby</Button>

                                {joinLobbyError &&
                                <span style={{color: red[4]}}>Die lobby bestaat niet</span>
                                }
                            </Col>
                        </Row>

                        <Row justify="center">
                            <span className={'lobby-options-or'}>of</span>
                        </Row>

                        <Row justify="center">
                            <Col>
                                <Button type="primary"
                                        onClick={() => {
                                            joinRandomLobby()
                                        }}>Join een willekeurige lobby</Button>
                            </Col>
                        </Row>
                    </Card>
                </Col>
            </Row>
            }
        </div>
    );
};

export default Lobby;
