import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Tabs, Tab, Form } from 'react-bootstrap';
import styled from 'styled-components';
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';
import "./Home.css"
import catchErrors from '../utils/catchErrors';

const socket = io();

const INIT_ROOM = {
  roomName: '',
  interest: '',
  roomId: '',
  member: '',
}
const INIT_LIST = [{
  interest: '',
  isOpen: '',
  memeber: [],
  roomId: '',
  roomName: '',
}]
const INIT_UNREAD = {
  roomCode: '',
  unreadcount: '',
}

function Home() {
  const userName = sessionStorage.getItem('name')
  const userId = sessionStorage.getItem('userId')
  const realTime = new Date().toISOString()

  const [error, setError] = useState('')

  const [checknew, setChecknew] = useState('')
  const [unreadnumber, setUnreadnumber] = useState(INIT_UNREAD)

  const [showModal, setShowModal] = useState(false);
  const [showEnter, setShowEnter] = useState(false);
  const [chat, setChat] = useState(false);
  const [open, setOpen] = useState(false);
  const [room, setRoom] = useState(INIT_ROOM)
  const [show, setShow] = useState(false)

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

  const [singleUser, setSingleUser] = useState('')
  const [recievedUser, setRecievedUser] = useState('')

  const [singleImg, setSingleImg] = useState('')
  const [recievedImg, setRecievedImg] = useState('')

  const [singleTime, setSingleTime] = useState('')
  const [recievedTime, setRecievedTime] = useState('')

  const handleCloseModal = () => {
    setShowModal(false);
    getClosedList()
    getOpenList()

  }
  const handleShowModal = () => setShowModal(true);
  const handleCloseEnter = () => setShowEnter(false);
  const handleShowEnter = () => setShowEnter(true);
  const handleChato = () => setChat(true);
  const handleChatc = () => setChat(false);
  const [closedlist, setClosedList] = useState(INIT_LIST);
  const [openlist, setOpenlist] = useState([])

  //SOCKET 관련 시작
  async function enterChatRoom(rCode) {    //방 입장하기
    socket.emit('joinRoom', rCode)
    socket.emit('newUser', { rmIf: rCode, userInfo: userName })
    setShow(true)
    console.log(`joinRoom : ${rCode} 입장`)
    console.log('HomePage/enterChatRoom 끝났습니다')
  }

  function closeChatRoom(rCode) {
    socket.emit('closeRoom', rCode)
    console.log(`${rCode}방 보기 중단`)
  }


  async function exitRoom(roomId) {
    const response = await axios.get('/users/check', { params: { '_id': userId } })
    const userNick = response.data.nickname;
    await axios.put('/room/deleteMem', { userId: userId, roomId: roomId })
    setSysmsg(`${userNick}님이 나갔습니다.`)
    setRoomCode("")
  }

  async function getClosedList() {
    const userid = sessionStorage.getItem('userId')
    let res = await axios.get('/room/closedlist', { params: { '_id': userid } })
    setClosedList(res.data)
  }

  async function getOpenList() {
    let res = await axios.get('/room/openlist')
    setOpenlist(res.data)
  }

  async function openListroom(roomId) {
    const roomInf = await axios.get('/room/changeMem', { params: { 'roomId': roomId } })
    setRoom(roomInf.data[0])
    setShow(false)
    setOpen(true)
  }
  //오픈채팅방에서 참가하기
  async function attendListRoom() {
    const roomId = room.roomId
    const tf = await axios.put('/room/changeMem', { userId: userId, roomId: roomId })
    const response = await axios.get('/users/check', { params: { '_id': userId } })
    const userNick = response.data.nickname;
    if (tf.data) {
      alert('참가되었습니다.')
      setSysmsg(`${userNick}님이 들어왔습니다.`)
      getClosedList()
      recordEntryLog()

    } else {
      alert('이미 참가된 방입니다.')
    }
  }

  async function recordEntryLog() {
    const leaveInfo = { userId: userId, roomCode: roomCode, leaveTime: realTime }
    try {
      const check = await axios.get('/room/entrylog', { params: leaveInfo })
      if (check.data) {       //있으면 put으로
        await axios.put('/room/entrylog', leaveInfo)
      } else {        //없으면 post
        await axios.post('/room/entrylog', leaveInfo)
      }
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  function enterButton() {
    setOpen(false)
  }
  const sendMsg = (e) => {
    e.preventDefault()
  }

  useEffect(() => {
    getClosedList();
    getOpenList();
  }, [roomCode]);

  useEffect(() => {
    if (!(singleChat === "")) {
      socket.emit("chat", {
        roomInfo: roomCode,
        sendInfo: {
          msg: singleChat,
          sender: singleUser,
          img: singleImg,
          time: singleTime
        }
      })
      setSingleChat("")
    }
  }, [singleChat])

  useEffect(() => {
    if (!(sysmsg === '')) {
      socket.emit("chat", {
        roomInfo: roomCode,
        sendInfo: {
          msg: sysmsg,
          sender: "system",
        }
      })
      setSysmsg('')
    }
  }, [sysmsg])



  const INIT_LEFT = {
    userId: '',
    roomCode: '',
    now: '',
  }
  const [leftInfo, setLeftInfo] = useState(INIT_LEFT)

  async function unreadMessage() {
    const userId = sessionStorage.getItem('userId')
    let leaveInfo = []
    try {
      for (let i = 0; i < closedlist.length; i++) {
        leaveInfo.push({ userId: userId, roomCode: closedlist[i].roomId, now: 0 })
      }
      for (let i = 0; i < closedlist.length; i++) {
        if (leaveInfo[i].roomCode === roomCode) {
          leaveInfo[i].now = '보는중'
        } else {
          leaveInfo[i].now = 0
        }
      }
      setUnreadnumber([''])
      const respond = await axios.get('/room/unreadMessage', { params: leaveInfo })
      setUnreadnumber(respond.data)
      setLeftInfo(leaveInfo)
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    socket.on("sendedMSG", (sendInfo) => {
      setRecievedTime(sendInfo.time)
      setRecievedImg(sendInfo.img)
      setRecievedUser(sendInfo.sender)
      setRecievedMsg(sendInfo.msg)
    })
    socket.on('checking', (check) => {
      console.log('클라이언트', check)
      setChecknew(check)
    })
  }, [])

  return (
    <div style={{ weight: "100vw", height: "100vh", backgroundColor: "" }}>
      <Menu style={{ weight: "100%", height: "10%" }} />
      <Row className="mr-0" style={{ weight: "100%", height: "80%" }}>
        <Col className="list" md={5}>
          <Sdiv chat={chat} open={open}>
            <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example" >
              <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
                <ClosedList closedlist={closedlist} leftInfo={leftInfo} checknew={checknew} unreadMessage={unreadMessage} unreadnumber={unreadnumber} setUnreadnumber={setUnreadnumber} userId={userId} singleChat={singleChat} recievedMsg={recievedMsg} enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
              </Tab>
              <Tab eventKey="open" title="공개방" onClick={handleChatc}>
                <OpenList openlist={openlist} enterChatRoom={enterChatRoom} openListroom={openListroom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode} closeChatRoom={closeChatRoom} />
              </Tab>
            </Tabs>
          </Sdiv>
        </Col>
        <Col style={{ padding: "5px", marginLeft: "15px" }}>
          {show ? <>
            {chat ? <Chat leftInfo={leftInfo} setLeftInfo={setLeftInfo} handleChatc={handleChatc} sendMsg={sendMsg} singleChat={singleChat} singleUser={singleUser} singleImg={singleImg} singleTime={singleTime} recievedMsg={recievedMsg} recievedUser={recievedUser} recievedImg={recievedImg} recievedTime={recievedTime} setSingleChat={setSingleChat} setSingleUser={setSingleUser} setSingleImg={setSingleImg} setSingleTime={setSingleTime} setRecievedMsg={setRecievedMsg} roomCode={roomCode} roomName={roomName} closeChatRoom={closeChatRoom} exitRoom={exitRoom} setRoomCode={setRoomCode} />
              : <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
                <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowModal} size="lg" block>생성</Button>
                <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} 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 mr-2" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', position: "relative" }}>
                  <h2 className="d-flex justify-content-center mb-3">현재 {room.roomName}방 입니다.</h2>
                  <h5>▷ 관심분야 : {room.interest}</h5>
                  <h5>▷ 참여인원 : {room.member.length}</h5>
                  <h5 className="mb-3">▷ 방코드(방코드를 통해서도 참여할 수 있습니다.) : {room.roomId}</h5>
                  <Row className='justify-content-center'>
                    <Button variant="outline" style={{ border: "3px solid", borderColor: "#b49dc9" }} size="sm" className="mr-4" onClick={enterButton}>뒤로가기</Button>
                    <Button variant="outline" style={{ border: "3px solid", borderColor: "#b49dc9" }} size="sm" className="ml-4" type='submit' onClick={attendListRoom}>참가</Button>
                  </Row>
                </div>
              </div>
            </div> : <div style={{ position: "fixed", bottom: "20px", right: "30px" }}>
                <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowModal} size="lg" block>생성</Button>
                <Button style={{ borderColor: "#9174ad", backgroundColor: "#9174ad", color: 'white' }} onClick={handleShowEnter} size="lg" block>참가</Button>
              </div>} </>}
        </Col>
      </Row>
      <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} />
      <EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName} sysmsg={sysmsg} setSysmsg={setSysmsg} />
    </div>
  );
}

const Sdiv = styled.div`
    @media screen and (max-width: 768px) {
     display: ${({ chat, open }) => {
    return (chat || open) ? 'none' : 'block'
  }}
   }
`

export default Home;