import "./Rooms.scss";
import { useState, useEffect } from "react";
import { createRoom, getRooms, deleteRoom } from "../../api";
import { Link } from "react-router-dom";

export default function Rooms() {
  const [rooms, setRooms] = useState([]);

  const onClickCreate = () => {
    const name = prompt("Nom de la piece ?");

    createRoom(name).then((res) => {
      const values = [...rooms];
      values.push(res);
      setRooms(values);
    });
  };

  const onClickDelete = (id, name) => {
    const confirmation = prompt(
      `Etes-vous sur de vouloir supprimer ${name} ? (Oui ou non)`,
      "non",
    );

    if (confirmation.toLocaleLowerCase() !== "oui") return;

    deleteRoom(id).then((res) => {
      const values = rooms.filter((e) => e._id !== id);
      setRooms(values);
    });
  };

  useEffect(() => {
    getRooms().then((res) => {
      setRooms(res);
    });
  }, []);

  return (
    <div id="rooms-container">
      {rooms.length === 0 ? (
        <span id="err-no-rooms">Aucune piece enregistree</span>
      ) : (
        <div id="rooms-list-container">
          {rooms.map((i, j) => (
            <div className="room" key={j}>
              <div
                className="room-delete"
                onClick={() => {
                  onClickDelete(i._id, i.name);
                }}
              >
                <span className="room-delete-ascii">×</span>
              </div>

              <div className="room-id-container">
                <span className="label-id">ID</span>
                <span className="room-id">
                  {i._id[0]}
                  {i._id[1]}
                  {i._id[2]}
                  {i._id[3]}
                  {i._id[4]}
                  {i._id[5]}
                  ...
                </span>
              </div>

              <div className="room-name-container">
                <span className="label-name">Nom&nbsp;</span>
                <Link to={`/room/${i._id}`}>
                  <span className="room-name">{i.name}</span>
                </Link>
              </div>
            </div>
          ))}
        </div>
      )}

      <div id="rooms-add-container">
        <div id="rooms-text-on">Creer une nouvelle piece</div>
        <button id="add-rooms" onClick={onClickCreate}>
          +
        </button>
      </div>
    </div>
  );
}
