import { observer } from "mobx-react-lite";
import { useLayoutEffect, useMemo, useState } from "react";
import { Button, Col, Input, Row } from "reactstrap";
import { toast } from "react-toastify";
import ReactTextareaAutosize from "react-textarea-autosize";
import { getMillis } from "taehui-ts/date";
import { useTo } from "taehui-ts/fe-utility";
import { useTranslation } from "react-i18next";

import { useAvatarStore } from "src/Stores";
import { wwwAXIOS } from "src/Www";
import Swal from "sweetalert2";

const ModifyAvatarView = observer(() => {
  const {
    taehuiAvatarID,
    taehuiAvatarName,
    taehuiFax,
    taehuiAvatarIntro,
    totem,
  } = useAvatarStore();
  const { t } = useTranslation();

  const [avatarCipher, setAvatarCipher] = useState("");
  const [avatarCipherModified, setAvatarCipherModified] = useState("");
  const [avatarName, setAvatarName] = useState(taehuiAvatarName);
  const [fax, setFax] = useState(taehuiFax);
  const [avatarIntro, setAvatarIntro] = useState(taehuiAvatarIntro);

  const to = useTo();

  const onQuit = () => {
    to("/");
  };

  const isValidFax = useMemo(() => /^.+@.+$/.test(fax), [fax]);

  useLayoutEffect(() => {
    if (!totem) {
      to("/avatar/w");
    }
  }, [to, totem]);

  return (
    <Row className="justify-content-center g-0">
      <Col className="m-1" xs="auto">
        <img
          alt=""
          src={`/www/avatar/drawing/${taehuiAvatarID}`}
          className="avatar route"
          onClick={() => {
            const inputElement = document.createElement("input");
            inputElement.type = "file";
            inputElement.accept = "image/png";
            inputElement.addEventListener("change", async ({ target }) => {
              const file = (target as HTMLInputElement).files?.[0];
              if (file) {
                const form = new FormData();
                form.append("data", file);
                const { status } = await wwwAXIOS.post(
                  "/avatar/drawing",
                  form,
                  {
                    headers: { millis: getMillis(), totem },
                  },
                );
                if (status === 201) {
                  window.location.reload();
                }
              }
            });
            inputElement.click();
          }}
        />
      </Col>
      <Col className="m-1" xs="auto">
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Input value={taehuiAvatarID} disabled />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Input
              valid={!!avatarCipher}
              invalid={!avatarCipher}
              type="password"
              placeholder={t("avatarCipher")}
              value={avatarCipher}
              onChange={({ target: { value } }) => {
                setAvatarCipher(value);
              }}
            />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Input
              type="password"
              placeholder={t("avatarCipherModified")}
              value={avatarCipherModified}
              onChange={({ target: { value } }) => {
                setAvatarCipherModified(value);
              }}
            />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Input
              valid={!!avatarName}
              invalid={!avatarName}
              placeholder={t("avatarName")}
              value={avatarName}
              onChange={({ target: { value } }) => {
                setAvatarName(value);
              }}
            />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Input
              valid={fax.length > 0 && isValidFax}
              invalid={fax.length > 0 && !isValidFax}
              type="email"
              placeholder={t("fax")}
              value={fax}
              onChange={({ target: { value } }) => {
                setFax(value);
              }}
            />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <ReactTextareaAutosize
              className="form-control"
              placeholder={t("avatarIntro")}
              value={avatarIntro}
              onChange={({ target: { value } }) => {
                setAvatarIntro(value);
              }}
            />
          </Col>
        </Row>
        <Row className="g-0">
          <Col className="m-1" xs="auto">
            <Button
              color="success"
              onClick={async () => {
                if (avatarCipher && avatarName && (!fax || isValidFax)) {
                  const { status, data } = await wwwAXIOS.put(
                    "/avatar",
                    {
                      avatarCipher,
                      avatarCipherModified,
                      avatarName,
                      fax,
                      avatarIntro,
                    },
                    {
                      headers: {
                        millis: getMillis(),
                        totem,
                      },
                    },
                  );
                  switch (status) {
                    case 204:
                      if (data) {
                        await Swal.fire(
                          t("doModifyAvatar"),
                          t("doModifiedAvatar"),
                          "success",
                        );
                        window.location.href = "/";
                      } else {
                        onQuit();
                      }
                      break;
                    case 403:
                      toast.error(t("failedValidateCipher"));
                      break;
                  }
                } else {
                  toast.error(t("failedValidation"));
                }
              }}
            >
              {t("doModifyAvatar")}
            </Button>
          </Col>
          <Col className="m-1" xs="auto">
            <Button color="danger" onClick={onQuit}>
              {t("quit")}
            </Button>
          </Col>
        </Row>
      </Col>
    </Row>
  );
});

export default ModifyAvatarView;
