import { useRouter } from "next/router";
import { useContext, useEffect, useState } from "react";
import {
  useWebsocketContext,
  WebsocketContext,
} from "../../context/websocket.context.js";
import { checkRoom, getRoom, joinRoom } from "../../requests/requests.room.js";
import styles from "../../styles/room/join.module.scss";
import { parseClassName } from "../../utils/utils.js";
import Layout from "../Layout.js";

export default function Join() {
  const [infos, setInfos] = useState({
    nick: "",
    pin: "",
    reconnectCode: "",
    joined: null,
  });
  const router = useRouter();
  const { connect, send, isConnected } = useContext(WebsocketContext);
  useEffect(() => {
    if (router.query.mode.length == 2) {
      checkRoom(router.query.mode[1])
        .then((res) => {
          console.log("SerInfos");
          connect(`ws://192.168.1.18:8000/ws/room/${res.id_code}`);
          setInfos({ ...infos, pin: res.id_code, joined: false });
        })
        .catch((err) => {
          router.push({ pathname: "/room/join" }, undefined, { shallow: true });
        });
    }
  }, []);
  const [errorRoom, setErrorRoom] = useState({ message: "" });
  return (
    <Layout page = "Rejoindre une salle">
      <main className={parseClassName(["container", styles.main])}>
        <div className={styles.form}>
          {infos.joined == null && (
            <>
              <h1 className={styles.title}>Rejoindre une salle</h1>
              <input
                type="text"
                placeholder="Entrer un code..."
                className="exo-input marginb-p0"
                value={infos.pin}
                onChange={(e) => {
                  setInfos({ ...infos, pin: e.target.value });
                }}
              />
              <p className="error-msg margint-p0">{errorRoom.message}</p>
              <button
                className="exo-btn margint-p2"
                onClick={() => {
                  checkRoom(infos.pin)
                    .then((res) => {
                      setErrorRoom({ message: "" });
                      console.log(res, "errrrrrr", res.id_code);
                      connect(`ws://192.168.1.18:8000/ws/room/${res.id_code}`);
                      setInfos({ ...infos, joined: false });
                    })
                    .catch((err) => {
                      console.log(err);
                      if (err.response.data.code == "111") {
                        setInfos({ ...infos, joined: false });
                        setErrorRoom({ message: "" });
                      } else if (err.response.data.code == "4044") {
                        setErrorRoom({ message: err.response.data.error });
                      }
                    });
                }}
              >
                Rejoindre !
              </button>
            </>
          )}
          {infos.joined == false && (
            <>
              <h1 className={styles.title}>Entrez un pseudo</h1>
              <input
                type="text"
                placeholder="Pseudo..."
                className="exo-input marginb-p0"
                value={infos.nick}
                onChange={(e) => {
                  setInfos({ ...infos, nick: e.target.value });
                }}
              />
              <p className="error-msg margint-p0">{errorRoom.message}</p>
              <button
                className="exo-btn margint-p2"
                onClick={() => {
                  /* router.push(
                { pathname: `/room/${res.id_code}`, query: { action: "view" } },
                undefined,
                {
                  shallow: true,
                }
              ); */
                  if (isConnected != false) {
                    send({
                      data: {
                        type: "login",
                        nick: infos.nick,
                      },
                    });
                  }
                }}
              >
                Rejoindre !
              </button>

              <h1 className={styles.title}>Ou un code de reconnexion</h1>
              <input
                type="text"
                placeholder="Pseudo..."
                className="exo-input marginb-p0"
                value={infos.reconnectCode}
                onChange={(e) => {
                  setInfos({ ...infos, reconnectCode: e.target.value });
                }}
              />
              <p className="error-msg margint-p0">{errorRoom.message}</p>
              <button
                className="exo-btn margint-p2"
                onClick={() => {
                  /* router.push(
                { pathname: `/room/${res.id_code}`, query: { action: "view" } },
                undefined,
                {
                  shallow: true,
                }
              ); */
                  if (isConnected) {
                    send({
                      data: {
                        type: "relogin",
                        code: infos.reconnectCode,
                      },
                    });
                  }
                }}
              >
                Rejoindre !
              </button>
            </>
          )}
        </div>
      </main>
    </Layout>
  );
}
