import React, { useState } from 'react'
import axios from 'axios';
import { Row, Col, Modal, Button, Form } from 'react-bootstrap';
import catchErrors from '../utils/catchErrors'


function EnterRoom(props) {
    const [enterCode, setEnterCode] = useState('');
    const [error, setError] = useState('');
    const realTime = new Date().toISOString()

    const userId = sessionStorage.getItem('userId');
    async function recordEntryLog() {
        const leaveInfo = { userId: userId, roomCode: enterCode, 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 handleChange(event) {
        const { name, value } = event.target
        setEnterCode(value)
        console.log(enterCode)
    }
    async function handleSubmit(event) {
        event.preventDefault()
        try {
            setError('')
            let res = await axios.post('/room/enterRoom', { enterCode })
            await axios.put('/room/member', { userId: userId, roomId: enterCode })
            const response = await axios.get('/users/check', { params: { '_id': userId } })
            const userNick = response.data.nickname;
            props.setRoomName(res.data)
            props.setRoomCode(enterCode)
            props.setSysmsg(`${userNick}님이 들어왔습니다.`)
            props.enterChatRoom(enterCode)
            props.handleCloseEnter()
            props.handleChato()
            setEnterCode('')
            recordEntryLog()
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    return (
        <>
            <Modal show={props.showEnter} onHide={props.handleCloseEnter}>
                <Modal.Header closeButton>
                    <Modal.Title>참여 코드로 채팅 참가</Modal.Title>
                </Modal.Header>
                {error && <Alert variant='danger'>
                    {error}
                </Alert>}
                <Modal.Body>
                    <Form onSubmit={handleSubmit}>
                        <Form.Group as={Row} controlId="formCodeE">
                            <Form.Label column sm={4}>참여 코드</Form.Label>
                            <Col>
                                <Form.Control name='roomCode' type='text' value={enterCode} onChange={handleChange} />
                            </Col>
                        </Form.Group>
                        <Form.Group as={Row}>
                            <Col sm={{ span: 5, offset: 4 }}>
                                <Button type="submit" style={{ backgroundColor: "#9174ad", borderColor: "#9174ad" }} >참가</Button>
                            </Col>
                        </Form.Group>
                    </Form>
                </Modal.Body>
            </Modal>
        </>
    )
}

export default EnterRoom
