import wsAPI from "@/app/[language]/site/lib/wsAPI";
import { useSiteStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { UnlockFill } from "react-bootstrap-icons";
import Button from "react-bootstrap/Button";
import FormControl from "react-bootstrap/FormControl";
import InputGroup from "react-bootstrap/InputGroup";
import InputGroupText from "react-bootstrap/InputGroupText";
import Modal from "react-bootstrap/Modal";
import ModalBody from "react-bootstrap/ModalBody";
import ModalFooter from "react-bootstrap/ModalFooter";
import Stack from "react-bootstrap/Stack";

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

export default observer(
  ({ siteID, siteName }: { siteID: string; siteName: string }) => {
    const {
      setSiteWindowOpened,
      isSiteCipherWindowOpened,
      setSiteCipherWindowOpened,
    } = useSiteStore();
    const [siteCipher, setSiteCipher] = useState("");
    const t = useTranslations();

    const onEnterSite = () => {
      wsAPI.send({
        eventID: EventPB.Event.EventID.ENTER_SITE,
        text: JSON.stringify({ siteID, siteCipher }),
      });
      setSiteCipherWindowOpened(false);
      setSiteWindowOpened(false);
    };

    return (
      <Modal
        show={isSiteCipherWindowOpened}
        onHide={() => {
          setSiteCipherWindowOpened(false);
        }}
      >
        <ModalBody>
          <Stack gap={2}>
            <InputGroup>
              <InputGroupText>{t("siteName")}</InputGroupText>
              <FormControl type="text" value={siteName} disabled />
            </InputGroup>
            <InputGroup>
              <InputGroupText>{t("siteCipher")}</InputGroupText>
              <FormControl
                type="password"
                value={siteCipher}
                placeholder={t("siteCipher")}
                onChange={({ target: { value } }) => {
                  setSiteCipher(value);
                }}
                onKeyDown={({ key }) => {
                  if (key === "Enter") {
                    onEnterSite();
                  }
                }}
              />
            </InputGroup>
          </Stack>
        </ModalBody>
        <ModalFooter>
          <Button variant="success" onClick={onEnterSite}>
            <UnlockFill />
          </Button>
        </ModalFooter>
      </Modal>
    );
  },
);
