import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { Form, Button, Row, Image, Col, Container } from 'react-bootstrap';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';

function Chat(props) {
  const [sender, setSender] = useState([])

  const [inner, setInner] = useState([''])
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지

  const [img, setImg] = useState([])
  const [time, setTime] = useState([''])
  const simpleTime = new Date().toLocaleTimeString()
  const usualTime = simpleTime.substring(0, simpleTime.length - 3)
  const realTime = new Date().toISOString()

  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

  const [exit, setExit] = useState(false);

  const userId = isAuthenticated()

  async function getProfile(userId) {
    try {
      const response = await axios.get(`/users/${userId}`)
      setUser(response.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  function handleChange(e) {
    e.preventDefault()
    setInner(e.target.value)
    setDisabled(false)
  }

  function sendMsgCH(e) {
    e.preventDefault()

    props.setSingleTime(usualTime)
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
    props.setSingleChat(inner)
    props.sendMsg(e)
    setInner('')
    setDisabled(true)
    // console.log('보내기', chat)
  }

  function handleClick() {
    setChat([''])
    props.closeChatRoom(props.roomCode)
    props.setRecievedMsg('')
    props.handleChatc()
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
    console.log('나간시간', realTime, usualTime)
  }

  function settingtime(hour) {
    let newhour = parseInt(hour) + 9
    if (newhour >= 24) {
      newhour -= 24
    }
    if (newhour >= 13) {
      newhour -= 12
      newhour = '오후 ' + newhour
    } else {
      newhour = '오전 ' + newhour
    }
    return newhour
  }

  //이전 채팅 내용에 대한 것 불러오기
  //프사 닉네임 메세지가 각각의 배열로 들어가서 띄워지는 방식
  async function getPreviousChat() {
    //메세지, 닉네임, 시간 불러오기
    const respond = await axios.get('/room/getChatInfo', { params: { 'roomCode': props.roomCode } })
    console.log(respond)
    const info = respond.data
    let chatlist = []
    let userlist = []
    let timelist = []
    let imglist = []
    let intlist = []
    for (let i = 0; i <= info.length - 1; i++) {  //사용하려는 형식에 맞게 수정 
      chatlist = [...chatlist, info[i].message]
      //userlist = [...userlist, info[i].username]
      if (info[i].username === "system") {
        userlist = [...userlist, ""]
        intlist.push(i)
        // continue;
      } else {
        userlist = [...userlist, info[i].username]
      }

      timelist = [...timelist, info[i].createdAt]
      // console.log('int', intlist)
      // console.log('timelist', timelist)
      let hour = timelist[i].split('T')[1].split(':')
      timelist[i] = settingtime(hour[0]) + ':' + hour[1]
    }
    console.log('userlist확인', userlist)

    //그 nick에 맞는 프사 불러오기
    const respond2 = await axios.get('/room/getProfileImage', { params: { 'userlist': userlist } })
    const imginfo = respond2.data
    for (let j = 0; j <= imginfo.length - 1; j++) {
      if (intlist.indexOf(j) < 0) {
        imglist = [...imglist, imginfo[j][0].profileimg]
      } else {
        imglist = [...imglist, ""]
      }
    }
    setChat(chatlist)
    setSender(userlist)
    setImg(imglist)
    setTime(timelist)
  }

  async function exitAndCloseRoom(){
    props.exitRoom(props.roomCode)
    setExit(false)
    props.handleChatc()
  }
  

  useEffect(() => {
    getProfile(userId)
  }, [userId])

  useEffect(() => {
    setTime([...time, props.singleTime])
    setImg([...img, props.singleImg])
    setSender([...sender, props.singleUser])
    setChat([...chat, props.singleChat])
    console.log('chat', chat)
    console.log('sender', sender)
  }, [props.singleChat])

  useEffect(() => {
    setTime([...time, props.recievedTime])
    setImg([...img, props.recievedImg])
    setSender([...sender, props.recievedUser])
    setChat([...chat, props.recievedMsg])
  }, [props.recievedMsg])

  useEffect(() => {
    getPreviousChat()
  }, [props.roomCode])

  useEffect(() => {
    getRoomName(props.roomCode)
    console.log('겟 룸네임', chat)
  }, [props.roomCode])

  const time = new Date().toLocaleTimeString()
  return (
    <>
      <Container id="chat" style={{ overflow: 'auto', padding: '20px', border: "2px solid", height: "500px", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
        <Row className="justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px" }}>
          <Col md="auto">
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
          </Col>
          <Col>
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {props.roomName} </Row>
            <Row > {props.roomCode} </Row>
          </Col>
          <Col md="auto">
            <Button variant="light" onClick={() => setExit(true)}>{'='}</Button>
          </Col>
        </Row>
        {exit ?
          <Row>
            <Col>퇴장하시겠습니까?</Col>
            <Col md="auto"><Button variant="light" onClick={exitAndCloseRoom}>{"나가기"}</Button></Col>
          </Row>
          : null}
        <p>{props.newUser}님이 입장하셨습니다.</p>
        {chat.map((value, index) => {
          if (!(value == '')) {
            if (!(sender[index] === user.nickname)) {
              return ( //상대편 메시지
                <Row key={index} className='m-1' >
                  <Col xs={2}>
                    <Image src={img && `/images/${img[index]}`} style={{ width: "50px", height: "50px" }} roundedCircle />
                  </Col>
                  <Col xs={8}>
                    <Row><strong>{sender[index]}</strong></Row>
                    <Row className='d-flex flex-wrap-nowrap'>
                      <Row className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Row>
                      <Col className='ml-1'>{time[index]}</Col>
                    </Row>
                  </Col>
                </Row>
              )
            } else if (sender[index] === "") {
              return (
                { value }
              )
            } else {
              return ( //내가 보낸 메시지
                <Row key={index} className='m-1 justify-content-end'>
                  <Row className='d-flex flex-wrap-nowrap' >
                    <Col className='mr-1'>{time[index]}</Col>
                    <Row className='mr-2' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
                  </Row>
                </Row>
              )
            }
          } else {
            return null
          }
        })
        }

      </Container >
      <Form onSubmit={sendMsgCH} fluid>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%', position: 'fixed' }} />
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
          </Button>
        </Form.Group>
      </Form>
    </>


  );
}


export default Chat;

