import { useState } from "react";
import type { PlasmoCSConfig, PlasmoGetInlineAnchor } from "plasmo";
import { sendToBackground } from "@plasmohq/messaging";
import { postPageMessage, waitPageMessage } from "~utils/pageMessage";

export const config: PlasmoCSConfig = {
  matches: ["https://www.bilibili.com/bangumi/media/*"],
};

export const getInlineAnchor: PlasmoGetInlineAnchor = () => {
  return document.querySelector(".bangumi-btn");
}

// Use this to optimize unmount lookups
// export const getShadowHostId = () => "plasmo-inline-example-unique-id"

const SyncButton = () => {
  const [status, setStatus] = useState(0);

  const onClick = () => {
    postPageMessage({ type: "toolbox::getBiliProgress" });

    waitPageMessage("toolbox::sendBiliProgress").then((res) => {
      if (res.type !== "toolbox::sendBiliProgress") {
        return;
      }

      if (!res.value) {
        setStatus(3);
        return;
      }

      console.log("Toolbox: 获得追番信息", res.value);

      sendToBackground({
        name: "bangumi",
        body: {
          action: "updateBangumiProgress",
          values: res.value,
        },
      }).then((res) => {
        if (res.status === "Success") {
          setStatus(1);
        }
        else {
          setStatus(2);
        }
      }).catch((e) => {
        if (e instanceof Error) {
          setStatus(2);
        }
      });
    });
  }

  const text = (() => {
    if (status === 0) {
      return "同步追番进度";
    }
    else if (status === 1) {
      return "✔️ 同步成功";
    }
    else if (status === 2) {
      return "❌ 同步失败";
    }
    else if (status === 3) {
      return "❌ 没有追过此番";
    }
  })();

  return (
    <button
      style={{
        fontSize: 18,
        color: "#fff",
        border: "3px solid transparent",
        borderRadius: 8,
        cursor: "pointer",
        padding: ".5em 1em",
        whiteSpace: "nowrap",
        background: "#f36392",
      }}
      onClick={onClick}
    >
      {text}
    </button>
  );
}

export default SyncButton;
