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

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

import "../css/lobby.sass";
import beer from "../img/beer.png"
import {RoomOptions} from "../types/types";

const {Option} = Select;

const Lobby = (props: any) => {
    // Form/control states.
    const [selectedRoomId, setSelectedRoomId] = useState(1);
    const [seekTime, setSeekTime] = useState(0);
    const [timelineName, setTimelineName] = useState(null);
    const [joiningLobby, setJoiningLobby] = useState(false);
    const [joinLobbyError, setJoinLobbyError] = useState(false);

    // Room and logic states.
    const isConnected = useIsConnected();
    const room = useRoom();
    const config = useConfig();

    // @ts-ignore
    const connectionType = connection.socket.io.engine.transport.name;

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

    function handleRequestStartClicked(e: MouseEvent) {
        connection.requestStart(seekTime * 1000);
    }

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

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

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

    function handleTimelineNameSet(timelineName: any) {
        setTimelineName(timelineName);
        connection.setRoomOptions(new RoomOptions(
            seekTime || 0,
            timelineName || room?.timelineName || ''))
    }

    function handleSetSeekTime(seekTime: number) {
        setSeekTime(seekTime);
        connection.setRoomOptions(new RoomOptions(
            seekTime * 1000 || 0,
            timelineName || room?.timelineName || ''))
    }

    let leaderConfig = (
        <Row justify="center">
            <Col>
                <Form
                    layout='horizontal'
                    labelCol={{span: 8}}
                    wrapperCol={{span: 24}}
                >
                    <Form.Item label="Starttijd">
                        <Input
                            type="number"
                            suffix="sec"
                            value={seekTime}
                            onChange={v => handleSetSeekTime(parseInt(v.target.value) || 0)}/>
                    </Form.Item>

                    <Form.Item label="Nummer">
                        <Select defaultValue={(room && room.timelineName) || ''}
                                onChange={e => handleTimelineNameSet(e)}>
                            {config && config.availableTimelines.map((item, i) =>
                                <Option key={item} value={item}>{item}</Option>
                            )}
                        </Select>
                    </Form.Item>

                </Form>

                <Button
                    block
                    type="primary"
                    onClick={handleRequestStartClicked}>Start</Button>
            </Col>
        </Row>
    )

    let nonLeaderConfig = (
        <Row justify="center">
            <Col>
                <p>
                    We gaan luisteren naar <b>{room && room.timelineName}</b> en
                    {room?.running && <span> zijn al gestart!</span>}
                    {!room?.running && <span> starten op {(room?.seekTime || 0) / 1000} seconden</span>}
                </p>

                <Button
                    block
                    type="primary"
                    disabled={!room || room.readyToParticipate}
                    onClick={handleJoin}>{room && room.readyToParticipate ? 'Wachten op het startsein' : 'Kom erbij'}</Button>
            </Col>
        </Row>
    )

    // @ts-ignore
    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={24} sm={16} md={12} xl={10}>
                    <Card>
                        <h3>Huidige lobby: <b>{room?.id || 'Geen lobby'}</b></h3>

                        {/*<span>Verbonden met {connectionType}</span>*/}

                        {room &&
                        <span>
                            {userCount === 1 ?
                                <p>Er is één gebruiker aanwezig.</p>
                                :
                                <p>Er zijn {userCount} gebruikers aanwezig.</p>
                            }
                        </span>
                        }
                        {room &&
                        <span>Deel de link met je vrienden om mee te doen!</span>
                        }
                        <br/>
                        <br/>

                        {room && (isLeader ? leaderConfig : nonLeaderConfig)}

                        <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={() => {
                                            handleJoinRandomLobby()
                                        }}>Join een willekeurige lobby</Button>
                            </Col>
                        </Row>
                    </Card>
                </Col>
            </Row>
            }
        </div>
    );
};

export default Lobby;
