import "./Rooms.scss";
import { useState, useEffect } from "react";
import { createRoom, getRooms, deleteRoom } from "../../api";
import { Link } from "react-router-dom";
import LoaderSpace from "../../components/LoaderSpace/LoaderSpace";
import AddBtn from "./../../components/AddBtn/AddBtn";
import { useAuth } from "../../hooks";
import { useParams } from "react-router-dom";
import { getRoomsLength } from "../../api";
import StylizedBtn from "../../components/StylizedBtn/StylizedBtn";

export default function Rooms() {
  const { _user } = useAuth();
  const [rooms, setRooms] = useState(null);
  const [isLoad, setIsLoad] = useState(true);
  const [isErr, setIsErr] = useState(false);
  const [displayRooms, setDisplayRooms] = useState(null);
  const { pageIndex } = useParams();
  const [virtualIndex, setVirtualIndex] = useState(0);
  const [roomsLen, setRoomLen] = useState(null);

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

    if (!name || name.length > 15) {
      alert("Assurez-vous que le nombre de characteres est inferieur a 15");
      return;
    }

    createRoom(name).then((res) => {
      setIsErr(false);
      const values = [...rooms];
      values.push(res);
      setRooms(values);
      alert(`Creation de la piece ${name} reussite !`);
    });
  };

  const configureRooms = (data) => {
    const splicer = (rms, datasPerPage) => {
      const partitions = [];
      let index = 0;

      while (index < rms.length) {
        partitions.push(rms.slice(index, index + datasPerPage));
        index += datasPerPage;
      }

      return partitions;
    };

    const newData = splicer(data, 8);
    const blabla = newData[pageIndex ? pageIndex : 0];

    if (pageIndex) {
      setVirtualIndex(parseInt(pageIndex, 10));
    }

    setRooms(newData);

    console.log(newData[pageIndex ? pageIndex : 0]);
    setDisplayRooms(newData[pageIndex ? pageIndex : 0]);

    if (!blabla) {
      window.location.href = "/rooms/0";
      setVirtualIndex(0);
    }
  };

  const handleBefore = () => {
    if (virtualIndex === 0) {
      return;
    }

    const index = virtualIndex - 1;
    console.log(rooms[index]);
    setDisplayRooms(rooms[index]);
    setVirtualIndex(index);
  };

  const handleNext = () => {
    if (virtualIndex >= rooms.length - 1) {
      return;
    }

    const index = virtualIndex + 1;
    console.log(rooms[index]);
    setDisplayRooms(rooms[index]);
    setVirtualIndex(index);
  };

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

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

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

      setRooms(values);
      setDisplayRooms(values[virtualIndex]);
      console.log(res);

      setRoomLen(roomsLen - 1);

      alert(`Vous venez de supprimer la piece ${name}`);
    });
  };

  useEffect(() => {
    document.title = `Pieces`;

    getRoomsLength().then((res) => {
      setRoomLen(res);
    });

    getRooms().then((res) => {
      if (res.length === 0) {
        setIsLoad(false);
        setIsErr(true);
        return;
      }

      setRooms(res);
      configureRooms(res);
    });
  }, []);

  return (
    <div id="rooms-container">
      <div id="rooms-headers">
        <h3 id="rooms-title">
          Voici vos{" "}
          {roomsLen ? roomsLen : <span id="rooms-title-loading">██</span>}{" "}
          pieces
        </h3>
      </div>

      {displayRooms ? (
        <div id="rooms-list-container">
          {displayRooms.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.slice(0, 6)}...</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>
      ) : (
        <LoaderSpace isVisible={isLoad} isCenterLoader={true} />
      )}

      {rooms ? (
        <div id="pagination-container">
          {virtualIndex > 0 ? (
            <StylizedBtn
              perso_style={{ width: "90px", height: "40px" }}
              text="Precedent"
              handle={handleBefore}
            />
          ) : null}

          <div id="pagination-index">{virtualIndex}</div>

          {virtualIndex < rooms.length - 1 ? (
            <StylizedBtn
              perso_style={{ width: "90px", height: "40px" }}
              text="Suivant"
              handle={handleNext}
            />
          ) : null}
        </div>
      ) : null}

      {isErr && !isLoad ? (
        <span id="err-no-rooms">Vous n'avez pas de piece pour le moment !</span>
      ) : null}

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