import React, { useState, useEffect } from 'react';
import { Form, Button, Row } from 'react-bootstrap';


function Chat(props) {
  let defaultname = sessionStorage.getItem('name');

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

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

  function sendMsgCH(e) {
    e.preventDefault()
    props.setSingleChat(inner)
    props.sendMsg(e)
    setInner('')
  }

  useEffect(() => {
    setChat([...chat, props.singleChat])
  }, [props.singleChat])
  
  useEffect(() => {
    setChat([...chat, props.recievedMsg])
  }, [props.recievedMsg])

  return (

    <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD" }}>
      <h2>현재 {props.roomName} 입니다.</h2>
      {      chat.map((value, index) => {
        if (!(value=='')) {
          // console.log(`value=${value}=`)
          return <Row key={index} className='ml-3'>
            {props.roomName}에서 {defaultname}님이 보낸 메세지 : {value}
          </Row>
        } else {
          return null
        }
      })}
      <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
      <Form onSubmit={sendMsgCH}>
        <Form.Group>
          <Form.Control name='chat' type="text" value={inner} onChange={handleChange} />
        </Form.Group>
        <Button variant="primary" type="submit">
          전송
        </Button>
      </Form>
    </div>


  );
}


export default Chat;
