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 INIT_ROOM = {
    name: '',
    owner: userId,
    member: userId,
    profileimg: '',
}

const CreateRoom = () => {
    const [room, setRoom] = useState(INIT_ROOM)
    const [error, setError] = useState("");
    const [success, setSuccess] = useState(false)
    const [disabled, setDisabled] = useState(true)

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

    function handleChange(event) {
        const { name, value, files } = event.target;
        if (files) {
            setRoom({ ...room, [name]: files[0] })
        } else {
            setRoom({ ...room, [name]: value })
        }
        console.log(room)
    }

    async function handleSubmit(e) {
        e.preventDefault()
        let formData = new FormData();
        console.log('profileimg:', room.profileimg)
        console.log('name:', room.name)
        formData.append("name", room.name);
        formData.append("userId", id);
        formData.append("profileimg", room.profileimg);
        try {
            const res = await roomApi.create(formData)
            console.log(res)
            const Id = res.id
            console.log(Id)
            alert(`방참여코드는 ${Id}입니다`)
            setSuccess(true)
        } catch (error) {
            catchErrors(error, setError);
        } finally {
            // setLoading(false);
        }
    }

    if (success) {
        // console.log('success', success)
        alert('룸생성이 완료되었습니다!')
        window.location.href=`/user/${id}`
        // return <Redirect to={`/user/${id}`} />
    }

    const { name, owner, member, profileimg } = room;

    return (
        <div className="modal-content" >
            <form onSubmit={handleSubmit}>
                <div className="modal-header">
                    <div className="modal-title" id="makeModal">
                        방생성하기
                    </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>}
                    <h6>방프로필사진</h6>
                    <div className="mb-4">
                        <input
                            type="file"
                            className="upload-hidden"
                            onChange={handleChange}
                            accept="image/*"
                            name="profileimg"
                        />
                    </div>
                    <h6>방이름</h6>
                    <div className="input-group">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="방이름을 입력해주세요"
                            aria-label="방이름 입력해주세요"
                            aria-describedby="basic-addon1"
                            onChange={handleChange}
                            name="name"
                        />
                    </div>
                    <div className="modal-footer">
                        <button type="submit" className="btn btn-primary">
                            생성
                        </button>
                    </div>
                </div>
            </form>
        </div >
    );
};

export default CreateRoom;