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

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

export default observer(() => {
  const { isNewSiteWindowOpened, setSiteWindowOpened, setNewSiteWindowOpened } =
    useSiteStore();
  const [siteName, setSiteName] = useState("");
  const [siteCipher, setSiteCipher] = useState("");
  const { t } = useTranslation();

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

  return (
    <Modal
      isOpen={isNewSiteWindowOpened}
      toggle={() => {
        setNewSiteWindowOpened(false);
      }}
      centered
    >
      <Row className="g-0">
        <Col className="m-1">
          <Input
            autoComplete="off"
            value={siteName}
            onChange={({ target: { value } }) => {
              setSiteName(value);
            }}
            placeholder={t("siteName")}
          />
        </Col>
      </Row>
      <Row className="g-0">
        <Col className="m-1">
          <Input
            autoComplete="off"
            value={siteCipher}
            onChange={({ target: { value } }) => {
              setSiteCipher(value);
            }}
            type="password"
            placeholder={t("siteCipher")}
            onKeyDown={({ key }) => {
              if (key === "Enter") {
                onNewSite();
              }
            }}
          />
        </Col>
      </Row>
      <Row className="justify-content-center g-0">
        <Col className="m-1" xs="auto">
          <Button onClick={onNewSite}>{t("inputNewSite")}</Button>
        </Col>
      </Row>
    </Modal>
  );
});
