import { useRouter } from "next/router";
import { useContext, useEffect, useState } from "react";
import { useSessionContext } from "../../context/session.context.js";
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 { isBrowser, isEmpty, parseClassName } from "../../utils/utils.js";
import Input from "../Input.jsx";
import Layout from "../Layout.js";

import { MdKeyboardArrowDown } from "react-icons/md";

export default function Join() {
  const [infos, setInfos] = useState({
    nick: "",
    pin: "",
    reconnectCode: "",
    joined: null,
  });
  const router = useRouter();
  const { connect, send, isConnected } = useContext(WebsocketContext);

  const { authData } = useSessionContext();
  useEffect(() => {
    if (!isEmpty(authData)) {
      setInfos({ ...infos, nick: authData.username });
    }
  }, [authData]);

  useEffect(() => {
    if (router.query.mode.length == 2) {
      checkRoom(
        router.query.mode[1],
        isBrowser && isEmpty(authData) && sessionStorage.getItem("clientId")
      )
        .then((res) => {
          connect(`/ws/room/${res.id_code}`);
          if (res.is_auth) {
            router.push({ pathname: "/room/" + res.id_code }, undefined, {
              shallow: true,
            });
          } else {
            setInfos({ ...infos, pin: res.id_code, joined: false });
          }
        })
        .catch((err) => {
          router.push({ pathname: "/room/join" }, undefined, { shallow: true });
        });
    }
    return () => {
      setInfos({ nick: "", pin: "", reconnectCode: "", joined: null });
    };
  }, []);

  const [errorRoom, setErrorRoom] = useState({ message: "" });
  useEffect(() => {
    if (
      !isEmpty(authData) &&
      infos.joined == false
    ) {
      if (isConnected) {
        send({
          data: {
            type: "login",
            nick: "",
          },
        });
      }
    }
  }, [infos.joined, isConnected, authData]);

  const [fade, setFade] = useState(null);
  useEffect(() => {
    if (fade != null) {
      setTimeout(() => {
        setInfos({ ...infos, joined: !fade });
      }, 300);
    }
  }, [fade]);

  const [active, setActive] = useState(false);
  return (
    <Layout page="Rejoindre une salle">
      <div className={styles.main}>
        {infos.joined == null && (
          <div
            className={parseClassName([
              styles.form,
              fade ? styles.swipe : undefined,
            ])}
          >
            <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, (isBrowser && isEmpty(authData)) && sessionStorage.getItem('clientId'))
                  .then((res) => {
                    setErrorRoom({ message: "" });
                    connect(`/ws/room/${res.id_code}`);
                    if (res.is_auth) {
                      router.push(
                        { pathname: "/room/" + res.id_code },
                        undefined,
                        {
                          shallow: true,
                        }
                      );
                    }
                    setFade(true);
                    router.push(
                      { pathname: "/room/join/" + res.id_code },
                      undefined,
                      {
                        shallow: true,
                      }
                    );
                  })
                  .catch((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 });
                    }
                  });
              }}
            >
              {isBrowser && localStorage.getItem("token") !== null
                ? "Rejoindre !"
                : "Suivant !"}
            </button>
          </div>
        )}
        {infos.joined == false && (
          <div className={styles.form}>
            <h1 className={styles.title}>Entrez un pseudo</h1>
            <Input
              type="text"
              disabled={active}
              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>
            <p
              onClick={() => {
                setActive(!active);
              }}
              className={parseClassName([
                styles.activeToggler,
                active ? styles.active : styles.unactive,
              ])}
            >
              <MdKeyboardArrowDown /> Avec un code de reconnexion
            </p>
            {active && (
              <Input
                type="text"
                placeholder="Code"
                className="marginl-p10"
                value={infos.reconnectCode}
                onChange={(e) => {
                  setInfos({ ...infos, reconnectCode: e.target.value });
                }}
              />
            )}
            <button
              className="exo-btn margint-p2"
              onClick={() => {
                if (isConnected && !active) {
                  send({
                    data: {
                      type: "login",
                      nick: infos.nick,
                    },
                  });
                } else if (isConnected && active) {
                  send({
                    data: {
                      type: "relogin",
                      code: infos.reconnectCode,
                    },
                  });
                }
              }}
            >
              Rejoindre !
            </button>
          </div>
        )}
      </div>
    </Layout>
  );
}
