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';
import { BsCaretLeftFill, BsList, BsExclamationCircleFill, BsCheck, BsX } from "react-icons/bs";
import { FiSend } from "react-icons/fi";

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)
    //console.log(chat)
  }

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

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

    props.handleChatc()
    props.setLeaveInfo([...props.leaveInfo, { roomName: props.roomCode, leaveTime: realTime }])
  }

  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 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()
    // console.log('겟 룸네임', chat)
  }, [props.roomCode])


  return (
    <div id="chat" style={{ display: "flex", flexDirection: "column", borderStyle: "solid", borderRadius: "5px", borderColor: "#4A5D7E", backgroundColor: "#FFFFFF", padding: '15px', width: "100%", height: "580px", position: "relative" }}>
      <div id="chat-head" style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center", width: "100%", height: "80px" }}>
        <a href="#;" onClick={handleClick} style={{ margin: "0px 0px 0px 15px" }}><BsCaretLeftFill size="20" color="#333333" /></a>
        <div style={{ justifyContent: "center" }}>
          <p style={{ color: "#333333", fontWeight: "bold", fontSize: "1.6em", textAlign: "center", margin: "0px 0px 0.5px 0px" }}> {props.roomName} </p>
          <p style={{ color: "#333333", fontSize: "0.8em", textAlign: "center", margin: "0.5px 0px 0px 0px" }}> {props.roomCode} </p>
        </div>
        <a href="#;" onClick={() => setExit(!exit)} style={{ margin: "0px 15px 0px 0px" }}><BsList size="20" color="#333333" /></a>
      </div>
      {exit ?
        <div id="chat-exit-check" style={{ display: "flex", flexDirection: "row", justifyContent: "space-evenly", alignItems: "center", margin: "1%", backgroundColor: "#30284D", borderRadius: "5px", height: "50px" }}>
          <p style={{ width: "70%", color: "#FAFAFA", fontSize: "1em", margin: "0px 10px 0px 20px" }}><BsExclamationCircleFill size="1em" color="#F2D788" />  퇴장하시겠습니까?</p>
          <a href="#;" onClick={exitAndCloseRoom}><BsCheck size="1em" color="#F2D788" /></a>
          <a href="#;" onClick={() => setExit(!exit)}><BsX size="1em" color="#F2D788" /></a>
        </div>
        : null}
      <div id="chat-body" style={{ overflow: 'auto', paddingRight: '15px', width: "95vw", height: "400px", background: '' }}>
        {chat.map((value, index) => {
          if (!(value.msg === '')) {
            if (value.sender === "system") {
              return (
                <Row style={{ background: "#F5F5F5", border: "none", justifyContent: "center" }}>
                  {value.msg}
                </Row>
              )
            } else if (!(value.sender === user.nickname)) {
              return ( 
                <Row key={index} className='d-flex flex-wrap-nowrap mt-2' style={{width:"100%"}}>
                  <Col xs="auto">
                      <Image src={value.img && `/images/${value.img}`} style={{ width: "55px", height: "55px" }} roundedCircle />
                  </Col>
                  <Col className="ml-2 d-flex flex-wrap-nowrap">
                    <Row><strong>{value.sender}</strong></Row>
                    <Row className='d-flex flex-wrap-nowrap'>
                      <Col style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: '#f1ebf7', borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Col>
                      <Col xs="auto">{value.time}</Col>
                    </Row>
                  </Col>
                </Row>
              )
            } else {
              return ( //내가 보낸 메시지
                <Row key={index} className='mt-2 justify-content-end' style={{width:"100%"}}>
                  <Row className='d-flex flex-wrap-nowrap' >
                    <Col xs="auto" className="ml-3">{value.time}</Col>
                    <Col className='mr-3' name='msg' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: "#d6c8e3", borderRadius: '5px', fontSize: 'x-large' }}>{value.msg}</Col>
                  </Row>
                </Row>
              )
            }
          } else {
            return null
          }
        })
        }
      </div>
      <div id="chat-low-side" style={{ width: "95%", height: "60px", position: "absolute", bottom: "0", padding: "10px 5px 5px 10px" }}>
        <div id="chat-form" style={{ width: "100%", height: "100%", borderStyle: "solid", borderWidth: "2px", borderColor: "#C1C1C1", borderRadius: "25px", padding: "3px 2px 2px 3px" }}>
          <Form onSubmit={sendMsgCH}>
            <Form.Group style={{ display: "flex", flexDirection: "row", justifyContent: "space-evenly" }}>
              <Form.Control name='chat' type="text" value={inner} onChange={handleChange} style={{ width: "80%", height: "90%", borderColor: "#FFFFFF" }} />
              <Button type="submit" disabled={disabled} style={{ justifyContent: "center", width: "10%", height: "90%", borderRadius: "20px", backgroundColor: "#C1C1C1", borderColor: "#FFFFFF" }}>
                <FiSend size="16px" color="#FAFAFA" />
              </Button>
            </Form.Group>
          </Form>
        </div>
      </div>
    </div>
  );
}


export default Chat;

