import usePostDrawing from "@/query/usePostDrawing";
import useWipeTotem from "@/query/useWipeTotem";
import { useTaehuiStore } from "@/state/Stores";
import { wwwAPIPath } from "@/utilities/wwwAPI";
import { observer } from "mobx-react-lite";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Back, PencilFill } from "react-bootstrap-icons";
import Button from "react-bootstrap/Button";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import Stack from "react-bootstrap/Stack";

export default observer<{ avatarID: string; avatarName: string }>(
  ({ avatarID, avatarName }) => {
    const { totem, setAvatarCipher, setAutoLogIn } = useTaehuiStore();

    const { push } = useRouter();

    const { mutateAsync: postDrawing } = usePostDrawing();
    const { mutateAsync: wipeTotem } = useWipeTotem();

    return (
      <Row className="flex-nowrap">
        <Col xs="auto">
          <Image
            unoptimized
            className="rounded border route"
            alt=""
            src={`${wwwAPIPath}/avatar/drawing/${avatarID}`}
            width={48}
            height={48}
            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) {
                  await postDrawing({ file });
                }
              });
              inputElement.click();
            }}
          />
        </Col>
        <Col>
          <Stack gap={2}>
            <span className="text-nowrap">
              {avatarName} ({avatarID})
            </span>
            <ButtonGroup>
              <Button
                variant="warning"
                disabled={!avatarID}
                onClick={() => {
                  push("/avatar");
                }}
              >
                <PencilFill />
              </Button>
              <Button
                disabled={!avatarID}
                variant="danger"
                onClick={async () => {
                  window.localStorage.removeItem("avatarID");
                  window.localStorage.removeItem("avatarCipher");
                  window.localStorage.removeItem("autoLogIn");
                  setAvatarCipher("");
                  setAutoLogIn(false);
                  await wipeTotem({ totem });
                }}
              >
                <Back />
              </Button>
            </ButtonGroup>
          </Stack>
        </Col>
      </Row>
    );
  },
);
