import { useState } from "react";
import { observer } from "mobx-react-lite";
import { Button, Col, Input, Modal, Row } from "reactstrap";
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(
  ({ siteID, siteName }: { siteID: string; siteName: string }) => {
    const {
      setSiteWindowOpened,
      isSiteCipherWindowOpened,
      setSiteCipherWindowOpened,
    } = useSiteStore();
    const [siteCipher, setSiteCipher] = useState("");
    const { t } = useTranslation();

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

    return (
      <Modal
        isOpen={isSiteCipherWindowOpened}
        toggle={() => {
          setSiteCipherWindowOpened(false);
        }}
        centered
      >
        <Row className="g-0">
          <Col className="m-1">
            <Input value={siteName} disabled />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1">
            <Input
              autoComplete="new-password"
              value={siteCipher}
              onChange={({ target: { value } }) => {
                setSiteCipher(value);
              }}
              type="password"
              placeholder={t("siteCipher")}
              onKeyDown={({ key }) => {
                if (key === "Enter") {
                  onEnterSite();
                }
              }}
            />
          </Col>
        </Row>
        <Row className="justify-content-center g-0">
          <Col className="m-1" xs="auto">
            <Button onClick={onEnterSite}>{t("enterSite")}</Button>
          </Col>
        </Row>
      </Modal>
    );
  },
);
