import wsAPI from "@/app/[language]/site/lib/wsAPI";
import CryptoJS from "crypto-js";
import { useTranslations } from "next-intl";
import { useState } from "react";
import Button from "react-bootstrap/Button";
import FormCheck from "react-bootstrap/FormCheck";
import FormControl from "react-bootstrap/FormControl";
import Stack from "react-bootstrap/Stack";

const EventPB = require("@/Event_pb");

export default function NotLoggedInAvatarView() {
  const [avatarID, setAvatarID] = useState("");
  const [avatarCipher, setAvatarCipher] = useState("");
  const [autoLogIn, setAutoLogIn] = useState(false);

  const t = useTranslations();

  const onLogIn = async () => {
    if (autoLogIn) {
      window.localStorage.setItem("avatarID", avatarID);
      window.localStorage.setItem(
        "avatarCipher",
        CryptoJS.AES.encrypt(
          avatarCipher,
          "591A6F91-2A27-4A88-88FA-0FEB7CB5FD94",
        ).toString(),
      );
    }
    window.localStorage.setItem("autoLogIn", autoLogIn.toString());
    wsAPI.send({
      eventID: EventPB.Event.EventID.LOG_IN,
      text: JSON.stringify({ avatarID, avatarCipher }),
    });
  };

  return (
    <Stack gap={2}>
      <FormControl
        type="text"
        placeholder={t("avatarID")}
        value={avatarID}
        onChange={({ target: { value } }) => {
          setAvatarID(value);
        }}
      />
      <FormControl
        type="password"
        placeholder={t("avatarCipher")}
        value={avatarCipher}
        onChange={({ target: { value } }) => {
          setAvatarCipher(value);
        }}
      />
      <Button className="text-nowrap" variant="success" onClick={onLogIn}>
        {t("logIn")}
      </Button>
      <FormCheck
        className="text-nowrap"
        id="autoLogIn"
        label={t("autoLogIn")}
        checked={autoLogIn}
        onChange={() => {
          setAutoLogIn(!autoLogIn);
        }}
      />
    </Stack>
  );
}
