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 { PencilFill } 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(() => {
  const { isNewSiteWindowOpened, setSiteWindowOpened, setNewSiteWindowOpened } =
    useSiteStore();
  const [siteName, setSiteName] = useState("");
  const [siteCipher, setSiteCipher] = useState("");
  const t = useTranslations();

  const onNewSite = () => {
    wsAPI.send({
      eventID: EventPB.Event.EventID.NEW_SITE,
      text: JSON.stringify({
        siteName: siteName,
        siteCipher: siteCipher,
        isNetSite: false,
      }),
    });
    setNewSiteWindowOpened(false);
    setSiteWindowOpened(false);
  };

  return (
    <Modal
      show={isNewSiteWindowOpened}
      onHide={() => {
        setNewSiteWindowOpened(false);
      }}
    >
      <ModalBody>
        <Stack gap={2}>
          <InputGroup>
            <InputGroupText>{t("siteName")}</InputGroupText>
            <FormControl
              type="text"
              value={siteName}
              onChange={({ target: { value } }) => {
                setSiteName(value);
              }}
              placeholder={t("siteName")}
            />
          </InputGroup>
          <InputGroup>
            <InputGroupText>{t("siteCipher")}</InputGroupText>
            <FormControl
              type="password"
              value={siteCipher}
              placeholder={t("siteCipher")}
              onChange={({ target: { value } }) => {
                setSiteCipher(value);
              }}
              onKeyDown={({ key }) => {
                if (key === "Enter") {
                  onNewSite();
                }
              }}
            />
          </InputGroup>
        </Stack>
      </ModalBody>
      <ModalFooter>
        <Button variant="success" onClick={onNewSite}>
          <PencilFill />
        </Button>
      </ModalFooter>
    </Modal>
  );
});
