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 [sender, setSender] = useState([])

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

  const [img, setImg] = useState([])

  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 } })
      console.log(res.data)
      setRoomName(res.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

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

  function sendMsgCH(e) {
    e.preventDefault()

    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
    props.setSingleChat(inner)

    props.sendMsg(e)
    setInner('')
    setDisabled(true)
  }

  function handleClick() {
    props.setRecievedMsg('')
    setChat([])
    props.handleChatc()
  }

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

  useEffect(() => {
    setImg([...img, props.singleImg])
    setSender([...sender, props.singleUser])
    setChat([...chat, props.singleChat])
  }, [props.singleChat])

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

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

  const time = new Date().toLocaleTimeString()
  return (
    <>
      <Container id="chat" style={{ padding: '20px', border: "2px solid", height: "520px", margin: "1%", borderColor: "#9174ad", background: '' }}>
        <Row className="d-flex justify-content-center" style={{ border: "2px solid", borderWidth: "medium", borderColor: "#9174ad", height: "80px", margin: "1%" }}>
          <Col md="auto">
            <Button variant="light" onClick={handleClick} >{`<`}</Button>
          </Col>
          <Col>
            <Row style={{ fontWeight: "bold", fontSize: "x-large" }}> {roomName} </Row>
            <Row > {props.roomCode} </Row>
          </Col>
        </Row>
        <div className="m-2" style={{ overflow: 'auto', padding: '20px', margin: "1%", height: "380px" }}>
          <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 style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: '#f1ebf7', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Row>
                        <Col className='ml-1'>{time}</Col>
                      </Row>
                    </Col>
                  </Row>
                )
              } else {
                return (
                  <Row key={index} className='m-1 justify-content-end'>
                    <Row className='d-flex flex-wrap-nowrap' >
                      <Col className='mr-1'>{time}</Col>
                      <Row className='mr-2' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: "#d6c8e3", borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
                    </Row>
                  </Row>
                )
              }
            } else {
              return null
            }
          })
          }
        </div>
      </Container >
      <Form onSubmit={sendMsgCH}>
        <Form.Group className="d-flex justify-content-center flex-wrap-nowrap mt-2 ml-4" style={{ width: '95%' }}>
          <Form.Control name='chat' type="text" value={inner} onChange={handleChange} style={{ borderColor: "#9174ad" }} />
          <Button className="ml-1" type="submit" disabled={disabled} style={{ width: '25%', backgroundColor: "#9174ad", borderColor: "#9174ad" }}>전송</Button>
        </Form.Group>
      </Form>
    </>
  );
}


export default Chat;

