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';


const INIT_CHAT = {
  msg: '',
  sender: '',
  img: '',
  time: ''
}

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

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

  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)
  }


  async function recordEntryLog() {
    const leaveInfo = { userId: userId, roomCode: props.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 handleClick() {
    props.closeChatRoom(props.roomCode)
    props.setRecievedMsg('')
    props.handleChatc()
    setChat([''])


    recordEntryLog()

    //아니 0으로 바꿔도 개수 세는걸 업데이트안하니까 소용없음 usestate해서 useEffect에 leaveInfo를 달아줘야할듯@@@@
    //누르면 now를 0으로
    // for (let i = 0; i < props.closedlist.length; i++) {
    //   props.leaveInfo[i].now = 0  //그냥 싹다 0으로 해도되잖아?
    //   if (props.leaveInfo[i].roomCode === props.roomCode) {
    //     // setLeftInfo(leftInfo[i].now='보는중')
    //     props.leaveInfo[i].now = 0   // 방 나가면 안 보는중으로 하기 위해 0으로 바꾸기!!!!!@@@@@@@@@@
    //     //usestate로 해보기@@@@@@
    //     console.log(i, '아아아아아아아아')
    //   } else {
    //     props.leaveInfo[i].now = 0
    //   }
    // }


  }

  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 } })
    const info = respond.data

    let intochat = []
    for (let prop in info) {
      let hour = info[prop].createdAt.split('T')[1].split(':')
      hour = settingtime(hour[0]) + ':' + hour[1]
      intochat.push({ msg: info[prop].message, sender: info[prop].username, img: info[prop].profileimg, time: hour })
    }
    setChat(intochat)
  }

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


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

  useEffect(() => {
    setChat([...chat, { msg: props.singleChat, sender: props.singleUser, img: props.singleImg, time: props.singleTime }])
  }, [props.singleChat])

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

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


  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}
        {chat.map((value, index) => {
          if (!(value.msg === '')) {
            if (!(value.sender === user.nickname)) {
              return (
                <Row key={index} className='m-1' >
                  <Col xs={2}>
                    <Image src={value.img && `/images/${value.img}`} style={{ width: "50px", height: "50px" }} roundedCircle />
                  </Col>
                  <Col xs={8}>
                    <Row><strong>{value.sender}</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.msg}</Row>
                      <Col className='ml-1'>{value.time}</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'>{value.time}</Col>
                    <Row className='mr-2' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value.msg}</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%' }} />
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
          </Button>
        </Form.Group>
      </Form>
    </>


  );
}


export default Chat;

