import { jsxs as l, Fragment as s, jsx as a } from "react/jsx-runtime";
import j from "@arcblock/ux/lib/LoadingMask";
import { Typography as T, TextField as B, Box as p, CircularProgress as R } from "@mui/material";
import { useMemoizedFn as d, useCreation as F, useReactive as D, useInterval as H } from "ahooks";
import c from "prop-types";
import { joinURL as K, withQuery as k } from "ufo";
import O from "@arcblock/ux/lib/Toast";
import q from "@arcblock/ux/lib/VerificationCode";
import { useEffect as N } from "react";
import v from "lodash/noop";
import U from "@arcblock/ux/lib/DIDConnect/provider-icon";
import V from "../../components/back-button.js";
import S from "../../components/action-button.js";
import { useStateContext as W } from "../../contexts/state.js";
import { BLOCKLET_SERVICE_PATH_PREFIX as G, VERIFY_CODE_LENGTH as Q, CHECK_STATUS_INTERVAL as X } from "../../../constant.js";
import { createAxios as Y, debug as y } from "../../../utils.js";
function $({
  fallback: A = null,
  state: o,
  forceUpdate: t = v,
  onSuccess: h = v,
  t: L = v
}) {
  const { setSelectedPlugin: w, locale: m, connectState: u, action: f, extraParams: P } = W(), n = d((r, i = {}) => L(r, i, m)), g = F(() => Y({
    baseURL: K(o.baseUrl, G, "/api/user")
  }), [o.baseUrl]), e = D({
    email: "",
    code: "",
    codeId: "",
    defaultVerifyMode: "magicLink",
    verifyMode: "magicLink",
    // magicLink, code
    loadingSendCode: !1,
    loadingVerifyCode: !1,
    error: ""
  }), b = d(() => {
    e.email = "", e.code = "", e.codeId = "", e.verifyMode = e.defaultVerifyMode, e.loadingSendCode = !1, e.loadingVerifyCode = !1, e.error = "";
  }), E = d(async () => {
    if (!e.email || !e.email.trim()) {
      e.error = n("emailRequired");
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.email)) {
      e.error = n("emailInvalid");
      return;
    }
    e.error = "";
    try {
      e.loadingSendCode = !0;
      let i = !1;
      ["login"].includes(f) && (u.sourceAppPid || (i = !0));
      const { data: x } = await g.post(k("/email/sendCode", { locale: m }), {
        email: e.email,
        sourceAppPid: u.sourceAppPid,
        useMagicLink: i
      });
      e.verifyMode = e.defaultVerifyMode, e.codeId = x.id, o.status = "sending";
    } catch (i) {
      const x = i?.response?.data?.error || i?.message;
      o.status = "error", o.error = x;
    } finally {
      e.loadingSendCode = !1, t();
    }
  }), I = d(async () => {
    if (e.code.length === Q)
      try {
        e.loadingVerifyCode = !0;
        const { data: r } = await g.post(k("/email/login", { locale: m }), {
          ...P,
          action: f,
          code: e.code,
          sourceAppPid: u.sourceAppPid
        });
        y("Email login succeed (use code)", { loginResult: r }), await h(
          {
            ...r,
            encrypted: !1
          },
          (i) => i
        ), o.status = "succeed";
      } catch (r) {
        const i = r?.response?.data || r?.message;
        O.error(i), y("Email login failed (use code)", { error: r });
      } finally {
        e.loadingVerifyCode = !1, t();
      }
  }), _ = d(async () => {
    o.status = "verifying", t();
    try {
      const { data: r } = await g.post(k("/email/login", { locale: m }), {
        ...P,
        action: f,
        magicToken: o.magicToken
      });
      y("Email login succeed (use magic link)", { loginResult: r }), await h(
        {
          ...r,
          encrypted: !1
        },
        (i) => i
      ), o.status = "succeed";
    } catch (r) {
      const i = r?.response?.data || r?.message;
      o.status = "error", o.error = i, y("Email login failed (use magic link)", { error: r });
    }
    t();
  }), M = e.verifyMode === "magicLink" && o.status === "sending" && // 如果正在校验验证码，则不轮询状态
  !e.loadingVerifyCode && e.codeId, z = d(async () => {
    if (M) {
      try {
        const { data: r } = await g.get("/email/status", {
          params: {
            codeId: e.codeId
          }
        });
        r.verified && (o.status = "succeed", b(), await h({ encrypted: !1 }, (i) => i));
      } catch (r) {
        console.error("check status error", r);
      }
      t();
    }
  });
  H(z, M ? X : void 0), N(() => {
    b(), (u.sourceAppPid || !["login"].includes(f)) && (e.defaultVerifyMode = "code"), o.magicToken && _();
  }, [o]);
  let C = null;
  if (o.status === "creating")
    C = /* @__PURE__ */ l(s, { children: [
      /* @__PURE__ */ a(
        T,
        {
          variant: "body2",
          sx: {
            textAlign: "center",
            color: "text.secondary"
          },
          children: n("emailPlaceholder")
        }
      ),
      /* @__PURE__ */ a(
        B,
        {
          name: "email",
          fullWidth: !0,
          type: "email",
          variant: "outlined",
          label: n("email"),
          placeholder: n("emailPlaceholder"),
          size: "small",
          value: e.email,
          onChange: (r) => {
            e.email = r.target.value;
          },
          onKeyDown: (r) => {
            r.key === "Enter" && E(e.email);
          },
          sx: {
            maxWidth: 320,
            "& .MuiOutlinedInput-root": {
              borderRadius: 1
            }
          },
          error: !!e.error,
          helperText: e.error,
          slotProps: {
            htmlInput: {
              sx: {
                boxSizing: "content-box !important"
              }
            }
          }
        }
      ),
      /* @__PURE__ */ l(p, { sx: { display: "flex", gap: 1 }, children: [
        /* @__PURE__ */ a(
          V,
          {
            onClick: () => {
              o.reset(), w();
            }
          }
        ),
        /* @__PURE__ */ l(
          S,
          {
            sx: {
              color: "primary.main",
              borderColor: "primary.light"
            },
            disabled: e.loadingSendCode,
            onClick: () => {
              E(e.email);
            },
            children: [
              e.loadingSendCode ? /* @__PURE__ */ a(R, { color: "inherit", size: 14, sx: { mr: 1 } }) : null,
              n("sendCode")
            ]
          }
        )
      ] })
    ] });
  else if (o.status === "sending")
    C = /* @__PURE__ */ l(s, { children: [
      /* @__PURE__ */ l(p, { sx: { display: "flex", flexDirection: "column", alignItems: "center" }, children: [
        /* @__PURE__ */ a(T, { variant: "body2", sx: { textAlign: "center", color: "text.secondary" }, children: e.verifyMode === "magicLink" ? /* @__PURE__ */ l(s, { children: [
          n("verifyEmail"),
          /* @__PURE__ */ a("br", {}),
          n("orUseCodePlaceholder")
        ] }) : n("codePlaceholder") }),
        /* @__PURE__ */ a(s, {})
      ] }),
      /* @__PURE__ */ l(s, { children: [
        /* @__PURE__ */ a(
          q,
          {
            code: e.code,
            onChange: (r) => {
              e.code = r;
            },
            onComplete: () => {
              I();
            }
          }
        ),
        /* @__PURE__ */ l(p, { sx: { display: "flex", gap: 1 }, children: [
          /* @__PURE__ */ a(
            V,
            {
              onClick: () => {
                e.code = "", o.status = "creating", t();
              }
            }
          ),
          /* @__PURE__ */ l(
            S,
            {
              sx: {
                color: "primary.main",
                borderColor: "primary.light"
              },
              disabled: e.loadingVerifyCode,
              onClick: () => {
                I();
              },
              children: [
                e.loadingVerifyCode ? /* @__PURE__ */ a(R, { color: "inherit", size: 14, sx: { mr: 1 } }) : null,
                n("confirm")
              ]
            }
          )
        ] })
      ] })
    ] });
  else
    return A;
  return /* @__PURE__ */ l(
    p,
    {
      sx: {
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        gap: 2,
        pb: 1
      },
      children: [
        /* @__PURE__ */ a(j, { size: 52, borderRadius: 12, children: /* @__PURE__ */ a(U, { provider: "email" }) }),
        C
      ]
    }
  );
}
$.propTypes = {
  fallback: c.any,
  state: c.object.isRequired,
  forceUpdate: c.func,
  onSuccess: c.func,
  t: c.func
};
export {
  $ as default
};
