import React, { useState, useEffect } from 'react';
import { Row, Col, Button } from 'react-bootstrap';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import ClosedList from '../Components/ClosedList';
import OpenList from '../Components/OpenList';
import Menu from '../Components/Menu';
import { io } from "socket.io-client";   //모듈 가져오기
import Chat from "../Components/Chat";
import RoomMake from "../Components/RoomMake"
import EnterRoom from "../Components/EnterRoom"
import axios from 'axios';

const socket = io();

const INIT_ROOM = {
    roomName: '',
    interest: '',
    roomId: '',
    member: '',
}

function Home() {
    const [showModal, setShowModal] = useState(false);
    const [showEnter, setEnter] = useState(false);
    const [chat, setChat] = useState(false);
    const [open, setOpen] = useState(false);
    const [room, setRoom] = useState(INIT_ROOM)

    //소켓
    const [singleChat, setSingleChat] = useState('')
    const [recievedMsg, setRecievedMsg] = useState('')
    const [roomName, setRoomName] = useState('')
    const [roomCode, setRoomCode] = useState('')

    const handleCloseModal = () => setShowModal(false);
    const handleShowModal = () => setShowModal(true);
    const handleCloseEnter = () => setEnter(false);
    const handleShowEnter = () => setEnter(true);
    const handleChato = () => setChat(true);
    const handleChatc = () => setOpen(true);



    //SOCKET 관련 시작
    //내채팅방에서 채팅시작
    function enterChatroom(rName) {    //방 입장하기
        socket.emit('joinRoom', rName)
        console.log(`joinRoom : ${rName} 입장`)
    }

    //오픈채팅방에서 참가하기
    async function openListroom(roomId) {
        console.log(roomId)
        const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } })
        console.log(roomInf)
        console.log(roomInf.data)
        console.log(roomInf.data.[0])
        setRoom(roomInf.data.[0])
    }

    async function attendListRoom() {
        const userId = sessionStorage.getItem('userId'); //sessionStorage에 저장된 userId가져옴
        const roomId = room.roomId
        const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
        if(tf.data) {
            alert('참가되었습니다.')
        } else {
            alert('이미 참가된 방입니다.')
        }
    }

    const sendMsg = (e) => {
        e.preventDefault()
    }

    useEffect(() => {
        socket.emit("chat", {
            roomName: roomCode,
            msg: singleChat
        })
    }, [singleChat])


    useEffect(() => {
        socket.on("sendedMSG", (msg) => {
            console.log(msg)
            setRecievedMsg(msg)
        })
    }, [])

    return (
        <>
            <Menu />
            <Row className="mr-0">
                <Col className="list" md={5}>
                    <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
                        <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
                            <ClosedList enterChatroom={enterChatroom} setRoomName={setRoomName} />
                        </Tab>
                        <Tab eventKey="open" title="공개방" onClick={handleChatc}>
                            <OpenList openListroom={openListroom} setRoomName={setRoomName} />
                        </Tab>
                    </Tabs>
                </Col>
                <Col style={{ padding: "0" }}>
                    {chat ?
                        <Chat handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} recievedMsg={recievedMsg} setSingleChat={setSingleChat} roomName={roomName} />
                        : <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
                            <Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
                            <Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
                        </div>}

                    {open ?
                        <div className="vh-90 flex-column align-items-center justify-content-center mt-2" variant="dark">
                            <div className="d-flex justify-content-center">
                                <div className="mt-5 p-5 shadow w-75">
                                    <h2 className="d-flex justify-content-center mb-3">현재 {room.roomName}방 입니다.</h2>
                                    <h5>▷ 관심분야 : {room.interest}</h5>
                                    <h5>▷ 참여인원 : {room.member.length}</h5>
                                    <h5>▷ 방코드(방코드를 통해서도 참여할 수 있습니다.) : {room.roomId}</h5>
                                    <Button className="d-flex flex-end mt-4" variant="primary" type="submit" onClick={attendListRoom}> 참가 </Button>
                                </div>
                            </div>
                        </div> :
                        <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
                            <Button variant="primary" onClick={handleShowModal} size="lg" block>생성</Button>
                            <Button variant="secondary" onClick={handleShowEnter} size="lg" block>참가</Button>
                        </div>}
                </Col>
            </Row>
            <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
            <EnterRoom showEnter={showEnter} enterChatRoom={enterChatroom} handleCloseEnter={handleCloseEnter} />
        </>
    );
}

export default Home;

