import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Col, Input } from "reactstrap";
import CryptoJS from "crypto-js";
import SiteComponent from "src/site/SiteComponent";

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

export default function NotSignedInInput() {
  const [avatarID, setAvatarID] = useState("");
  const [avatarCipher, setAvatarCipher] = useState("");
  const [autoSignIn, setAutoSignIn] = useState(false);
  const { t } = useTranslation();

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

  return (
    <>
      <Col className="m-1" xs="auto">
        <Input
          value={avatarID}
          onChange={({ target: { value } }) => {
            setAvatarID(value);
          }}
          placeholder={t("signInID")}
        />
      </Col>
      <Col className="m-1" xs="auto">
        <Input
          value={avatarCipher}
          onChange={({ target: { value } }) => {
            setAvatarCipher(value);
          }}
          type="password"
          placeholder={t("signInCipher")}
          onKeyDown={({ key }) => {
            if (key === "Enter") {
              onSignIn();
            }
          }}
        />
      </Col>
      <Col className="m-1" xs="auto">
        <Button color="success" onClick={onSignIn} value={t("signIn")} />
      </Col>
      <Col className="m-1" xs="auto">
        <Button
          color={autoSignIn ? "success" : "danger"}
          onClick={() => {
            setAutoSignIn((autoSignIn) => !autoSignIn);
          }}
        >
          {t("autoSignIn")}
        </Button>
      </Col>
    </>
  );
}
