import { useEffect, useState } from "react";
import { Redirect } from "react-router-dom";
import roomApi from "../../apis/room.api";
import catchErrors from "../../context/catchError";

const id = localStorage.getItem("user");

const JoinRoom = () => {
    const [roomId, setRoomId] = useState("");
    const [disabled, setDisabled] = useState(true);
    const [error, setError] = useState("");
    const [success, setSuccess] = useState(false);

    useEffect(() => {
        const isRoom = Object.values(roomApi).every((el) => Boolean(el));
        isRoom ? setDisabled(false) : setDisabled(true);
    }, [roomId]);

    function handleChange(event) {
        const { value } = event.target;
        setRoomId(value);
    }

    async function handleSubmit(e) {
        e.preventDefault();
        try {
            // setLoading(true);
            setError("");
            const data = await roomApi.join({ userId: id, roomId: roomId });
            console.log('서버연결됬나요', data)
            setSuccess(true);
        } catch (error) {
            catchErrors(error, setError);
        } finally {
            // setLoading(false);
        }
    }

    if (success) {
        // console.log('success', success)
        alert('룸참여가 완료되었습니다!')
        window.location.href=`/room/${roomId}/1`
    }

    return (
        <div className="modal-content">
            <form onSubmit={handleSubmit}>
                <div className="modal-header">
                    <div className="modal-title" id="joinModal">
                        방참여하기
                    </div>
                    <button
                        type="button"
                        className="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"
                    ></button>
                </div>
                <div className="modal-body">
                    {error && <div className="alert alert-danger">{error}</div>}
                    <div className="input-group mb-3">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="참여코드를 입력하세요"
                            aria-label="참여코드를 입력하세요"
                            aria-describedby="basic-addon1"
                            name="roomId"
                            value={roomId}
                            onChange={handleChange}
                        />
                    </div>
                    <div className="modal-footer">
                        <button
                            type="submit"
                            className="btn btn-primary">
                            확인
                        </button>
                    </div>
                </div>
            </form>
        </div>
    );
};

export default JoinRoom;
