import usePostGetTotem from "@/query/usePostGetTotem";
import { useTaehuiStore } from "@/state/Stores";
import CryptoJS from "crypto-js";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
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";

export default observer(() => {
  const { autoLogIn, avatarCipher, setAvatarCipher, setAutoLogIn } =
    useTaehuiStore();

  const t = useTranslations();

  const [avatarID, setAvatarID] = useState("");

  const { mutateAsync: postGetTotem } = usePostGetTotem();

  const { push } = useRouter();

  const onLogIn = async () => {
    await postGetTotem({ avatarID, avatarCipher });
    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());
  };

  const onEnroll = () => {
    push("/avatar");
  };

  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);
        }}
      />
      <Stack gap={2} direction="horizontal">
        <Button className="text-nowrap" variant="success" onClick={onLogIn}>
          {t("logIn")}
        </Button>
        <Button className="text-nowrap" onClick={onEnroll}>
          {t("enroll")}
        </Button>
      </Stack>
      <Stack gap={2} direction="horizontal">
        <FormCheck
          className="text-nowrap"
          id="autoLogIn"
          label={t("autoLogIn")}
          checked={autoLogIn}
          onChange={() => {
            setAutoLogIn(!autoLogIn);
          }}
        />
      </Stack>
    </Stack>
  );
});
