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) {
  // let defaultname = sessionStorage.getItem('name');

  const [roomName, setRoomName] = useState('')
  const [inner, setInner] = useState([''])
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지
  const [disabled, setDisabled] = useState(true)
  const [user, setUser] = useState('')
  const [error, setError] = useState('');

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

  async function getRoomName(roomCode) {
    try {
      let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
      setRoomName(res.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

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

  function sendMsgCH(e) {
    e.preventDefault()
    props.setSingleChat(inner)
    props.sendMsg(e)
    setInner('')
    setDisabled(true)
    console.log(chat)
  }
  useEffect(() => {
    getProfile(userId)
  }, [userId])

  useEffect(() => {
    setChat([...chat, props.singleChat])
    console.log('UseEffect singlechat', chat)
    // check()
  }, [props.singleChat])

  useEffect(() => {
    setChat([...chat, props.recievedMsg])
    console.log('UseEffect recievechat', chat)
  }, [props.recievedMsg])

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


  // function check() {
  //   // if (chat[chat.length-1].user ===chat[chat.length-2].user){  //마지막보낸거랑 그 전꺼랑 보낸사람이 같은지 비교
  //   if (chat.length === 2) {
  //     setHidden(false)
  //   } else {
  //     setHidden(true)
  //   }
  //   console.log(hidden)
  // }
  const time = new Date().toLocaleTimeString()
  return (
    <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
      <Row class="d-flex justify-content-center" style={{ border:"2px solid", borderWidth: "medium", borderColor: "#FFD75F", height: "80px", margin: "1%" }}>
        <Col md="auto">
          <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
        </Col>
        <Col>
          <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
          <Row > {props.roomCode} </Row>
        </Col>
      </Row>
      {/* <h2> 참여코드 : {props.roomCode} </h2> */}
      {/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */}
      {
        chat.map((value, index) => {
          if (!(value == '')) {
            return (
              <Row key={index} className='m-1 ml-3' >
                <Col xs={2}>
                  {user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "50px", height: "50px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "50px", height: "50px" }} roundedCircle />}
                </Col>
                <Col xs={8}>
                  <Row><strong>{user.nickname}의 {index}</strong></Row>
                  <Row className='d-flex flex-wrap-nowrap'>
                    <Col className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Col>
                    <Col className='ml-4'>{new Date().toLocaleTimeString()}</Col>
                  </Row>
                </Col>
              </Row>
            )
          } else {
            return null
          }
        })
      }
      {/* 내가 보낸 메세지 띄우기 */}
      {
        chat.map((value, index) => {
          if (!(value == '')) {
            return (
              <Row key={index} className='m-1 mr-4 justify-content-end'>
                <div className='d-flex flex-wrap-nowrap' >
                  <Row className='mr-4'>{time}</Row>
                  <Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
                </div>
              </Row>
            )
          } else {
            return null
          }
        })
      }






      <Form onSubmit={sendMsgCH}>
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center ml-2 mr-2'>
          <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>
    </div >


  );
}


export default Chat;
