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

const id = localStorage.getItem("user");
const INIT_ROOM = {
  roomId:"",
  name: "",
  profileimg: "",
  member: "",
};
const RoomSingle = () => {
  const [room, setRoom] = useState([INIT_ROOM]);
  const [error, setError] = useState("");
  const channelId = 'main';
  const {roomId}=useParams(room.roomId);
  async function getJoinRoom(Id) {
    try {
      const User = await userApi.getUser(Id);
      const RoomNumArr = User.roomNumber;
      const Room = await roomApi.getRoom(RoomNumArr);
      let roomlist = [];
      for (let prop in Room) {
        roomlist.push({
          roomId:Room[prop].id,
          name: Room[prop].name,
          profileimg: Room[prop].profileimg,
          member: Room[prop].member.length,
        });
      }
      setRoom(roomlist);
    } catch (error) {
      catchErrors(error, setError);
    }
  }
  useEffect(() => {
    getJoinRoom(id);
  }, [id]);
  console.log(room)

  const { profileimg } = room;
  return (
    <div>
      {room &&
        room.map((el) => (
          <Link
            to={`/room/${el.roomId}/${channelId}`}
            className="text-decoration-none text-dark"
          >
            <div
              className="d-flex mx-4 my-2 p-2"
              style={{ backgroundColor: "#C4C4C4" }}
            >
              <div style={{ width: "37px", height: "37px" }}>
                <img
                  src={`/roomUploads/${el.profileimg}`}
                  className="rounded-circle"
                  style={{ width: "37px", height: "37px" }}
                />
              </div>
              <div
                className="mx-3 mt-2"
                style={{
                  width: "250px",
                  overflow: "scroll",
                  whiteSpace: "nowrap",
                  msOverflowStyle: "none",
                }}
              >
                {el.name}
              </div>
              <div className="ms-auto mt-2"> {el.member}/100 </div>
            </div>
          </Link>
        ))}
    </div>
  );
};

export default RoomSingle;
