import { useState } from "react";
import { Button, Col, Input, Modal, Row } from "reactstrap";
import CryptoJS from "crypto-js";
import { observer } from "mobx-react-lite";
import { useTranslation } from "react-i18next";
import { useSiteStore } from "src/Stores";
import SiteComponent from "src/site/SiteComponent";

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

export default observer(() => {
  const { isSignInOpened, setSignInOpened } = useSiteStore();
  const { t } = useTranslation();

  const [avatarID, setAvatarID] = useState("");
  const [avatarCipher, setAvatarCipher] = useState("");
  const [autoSignIn, setAutoSignIn] = useState(false);

  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 (
    <Modal
      isOpen={isSignInOpened}
      toggle={() => setSignInOpened(false)}
      centered
    >
      <Row className="g-0">
        <Col className="m-1">
          <Input
            value={avatarID}
            onChange={({ target: { value } }) => {
              setAvatarID(value);
            }}
            placeholder={t("signInID")}
          />
        </Col>
      </Row>
      <Row className="g-0">
        <Col className="m-1">
          <Input
            value={avatarCipher}
            onChange={({ target: { value } }) => {
              setAvatarCipher(value);
            }}
            type="password"
            placeholder={t("signInCipher")}
            onKeyDown={({ key }) => {
              if (key === "Enter") {
                onSignIn();
              }
            }}
          />
        </Col>
      </Row>
      <Row className="justify-content-center g-0">
        <Col className="m-1" xs="auto">
          <Button color="success" onClick={onSignIn}>
            {t("signIn")}
          </Button>
        </Col>
        <Col className="m-1" xs="auto">
          <Button
            color={autoSignIn ? "success" : "danger"}
            onClick={() => {
              setAutoSignIn((prevState) => !prevState);
            }}
          >
            {t("autoSignIn")}
          </Button>
        </Col>
      </Row>
    </Modal>
  );
});
