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

const INIT_ROOM = {
    roomName: '',
    interest: '',
    isOpen: false
}

function RoomMake(props) {
    const [room, setRoom] = useState(INIT_ROOM);
    const [error, setError] = useState('');
    const [roomCode, setRoomCode] = useState('')

    const member = sessionStorage.getItem('userId');
    const realTime = new Date().toISOString()

    async function recordEntryLog(Id) {
        const leaveInfo = { userId: member, roomCode: Id, 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
        setRoom({ ...room, [name]: value, member })
    }

    async function handleSubmit(event) {
        event.preventDefault()
        try {
            setError('')
            let res = await axios.post('/room/makeRoom', room)
            const Id = res.data.roomId
            alert(`방암호는 ${Id}입니다`)
            props.handleCloseModal()
            setRoom(INIT_ROOM)
            recordEntryLog(Id)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    return (
        <Modal show={props.showModal} onHide={props.handleCloseModal}>
            <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="chatName">
                        <Form.Label column sm={4}>방 이름</Form.Label>
                        <Col>
                            <Form.Control name='roomName' type='text' value={room.roomName} onChange={handleChange} />
                        </Col>
                    </Form.Group>
                    <Form.Group as={Row} controlId="chatInterest">
                        <Form.Label column sm={4}>관심 분야</Form.Label>
                        <Col>
                            <Form.Control as="select" defaultValue="Choose..." name='interest' type='text' value={room.interest} onChange={handleChange}>
                                <option>Choose...</option>
                                <option>과학</option>
                                <option>수학</option>
                                <option>예술</option>
                                <option>언어</option>
                                <option>취미</option>
                            </Form.Control>
                        </Col>
                    </Form.Group>
                    <Form.Group as={Row} controlId="chatIsOpen">
                        <Form.Label column sm={4}>공개방</Form.Label>
                        <Col>
                            <Form.Check
                                type="checkbox"
                                checked={room.isOpen}
                                name='isOpen'
                                onChange={() => setRoom({ ...room, isOpen: !room.isOpen })} />
                        </Col>
                    </Form.Group>
                    {
                        (room.isOpen)
                            ? (<p><b>공개방</b>으로 개설되어 공개방 목록에 공개되며, 코드를 공유하여 참가할 수도 있습니다.</p>)
                            : (<p><b>비밀방</b>으로 개설되며, 참여자들에게 코드를 공유해야합니다.</p>)
                    }
                    <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 RoomMake
