import { jsx as i, jsxs as U } from "react/jsx-runtime";
import o from "prop-types";
import { Box as g } from "@mui/material";
import { LOGIN_PROVIDER as s, LOGIN_PROVIDER_NAME as te, LOGIN_PROVIDER_ICON_SIZE as h } from "@arcblock/ux/lib/Util/constant";
import { getWebWalletUrl as re } from "@arcblock/ux/lib/Util/wallet";
import L from "lodash/noop";
import { useMemoizedFn as I } from "ahooks";
import x from "js-cookie";
import { getCookieOptions as se } from "@arcblock/ux/lib/Util";
import { useRef as A, useEffect as ne } from "react";
import { mergeSx as ie } from "@arcblock/ux/lib/Util/style";
import le from "@arcblock/ux/lib/DIDConnect/provider-icon";
import { GA_LAST_LOGIN_METHOD as u } from "@arcblock/ux/lib/withTracker/constant";
import ae from "./mobile-login-item.js";
import ce from "./web-login-item.js";
import pe from "./login-method-item.js";
import { useOAuth as me } from "../../../OAuth/context.js";
import { useStateContext as ue } from "../../contexts/state.js";
import { getAppId as de, logger as fe, getApiErrorMessage as ge } from "../../../utils.js";
import he from "./passkey-login-item.js";
import { usePasskey as Le } from "../../../Passkey/context.js";
import "../../../Passkey/actions.js";
import ye from "../../plugins/email/index.js";
function Ie({
  onSuccess: b = L,
  onError: M = L,
  size: c = "small",
  tokenState: t,
  webWalletUrl: G = re(),
  tokenKey: S,
  passkeyBehavior: j = "none",
  onReset: y = L,
  showMobileLogin: V = !0,
  showOAuthLogin: v = !0,
  showPasskeyLogin: O = !0,
  showWebLogin: q = !0,
  showEmailLogin: d = !0,
  oauthProviderList: B = [],
  slotProps: K = {},
  disableSwitchApp: P = !1,
  forceUpdate: H = L,
  magicToken: E = void 0,
  baseUrl: Y = "/",
  customItems: Z = []
}) {
  const w = A(null), C = A(null), _ = A(null), { loginOAuth: $, logoutOAuth: z, t: f, oauthState: n } = me(), { passkeyState: R } = Le(), { extraParams: T, locale: J, connectState: r, plugins: W, setPlugins: Q, setSelectedPlugin: X, getPlugin: k, lastLoginMethod: l } = ue(), D = I(async (e) => {
    localStorage.setItem(u, e.provider), t.reset(), n.reset({
      status: "scanned"
    }), R.reset(), r.chooseMethod = e.provider;
    const p = T?.sourceAppPid;
    try {
      n.loading = !0, n.status = "scanned";
      const m = await $(e, {
        action: t.action,
        ...T
      }), a = se({ returnDomain: !1 });
      x.remove("connected_did", a), x.remove("connected_pk", a), x.remove("connected_wallet_os", a), m?.sessionToken && (await b(
        {
          ...m,
          encrypted: !1
        },
        (oe) => oe,
        {
          sourceAppPid: p,
          connected_app: de(t.appInfo, t.memberAppInfo)
        }
      ), n.loading = !1, n.status = "succeed");
    } catch (m) {
      fe.error(`Failed login OAuth: ${e.provider}`, m);
      const a = ge(m, f("loginOAuthFailed"));
      n.loading = !1, n.error = a, n.status = "error", await z({ provider: e.provider }), M(new Error(a));
    }
  }), N = I(async () => {
    t.reset(), await y(), t.status = "created", r.chooseMethod = "wallet";
  }), F = ye({ baseUrl: Y }), ee = I(() => {
    if (E && d && W.some((e) => e.name === s.EMAIL)) {
      const e = k(s.EMAIL);
      e.state.status === "idle" && (localStorage.setItem(u, s.EMAIL), e.state.reset(), e.state.magicToken = E, r.chooseMethod = s.EMAIL, X(e), H());
    }
  });
  return ne(() => {
    const e = [];
    if (d) {
      const p = k(s.EMAIL);
      p && p.baseUrl === F.baseUrl ? e.push(p) : e.push(F);
    }
    Q(e), r.retryConnect = N, setTimeout(() => {
      ee();
    }, 100);
  }, [d]), /* @__PURE__ */ i(g, { className: "did-connect__choose", sx: ie({ flex: 1 }, K?.root?.sx), children: /* @__PURE__ */ i(
    g,
    {
      sx: {
        display: "flex",
        flexDirection: "column",
        gap: 2
      },
      children: /* @__PURE__ */ U(
        g,
        {
          sx: [
            {
              display: "flex",
              flexDirection: "column",
              gap: 1.5
            }
          ],
          children: [
            V && /* @__PURE__ */ i(
              ae,
              {
                t: f,
                isLatest: l && l === s.WALLET,
                ref: w,
                tokenState: t,
                sx: [c === "small" ? { p: 1 } : { p: 2 }],
                locale: J,
                tokenKey: S,
                disableSwitchApp: P,
                onClick: async () => {
                  localStorage.setItem(u, s.WALLET), t.reset(), await y(), t.status = "created", r.chooseMethod = "wallet";
                  const e = w.current?.connect;
                  r.retryConnect = () => {
                    e(N);
                  };
                }
              }
            ),
            q && /* @__PURE__ */ i(
              ce,
              {
                isLatest: l && l === s.WALLET,
                ref: C,
                tokenState: t,
                webWalletUrl: G,
                t: f,
                sx: [c === "small" ? { p: 1 } : { p: 2 }],
                disableSwitchApp: P,
                onClick: () => {
                  localStorage.setItem(u, s.WALLET), t.status = "scanned", r.chooseMethod = "wallet-web";
                  const e = C.current.connect;
                  r.retryConnect = async () => {
                    await y(), t.error = "", t.status = "scanned", e();
                  };
                }
              }
            ),
            v || O || d ? /* @__PURE__ */ U(
              g,
              {
                sx: [
                  {
                    display: "flex",
                    flexDirection: "column",
                    gap: 1.5
                  }
                ],
                children: [
                  W.map(
                    (e) => e.renderListItem({
                      key: e.name,
                      sx: [c === "small" ? { p: 1 } : { p: 2 }]
                      // forceUpdate,
                    })
                  ),
                  v ? B.map((e) => /* @__PURE__ */ i(
                    pe,
                    {
                      t: f,
                      isLatest: l && l === e.provider,
                      title: te[e.provider],
                      icon: /* @__PURE__ */ i(
                        le,
                        {
                          provider: e.provider,
                          sx: {
                            transform: "scale(0.95)",
                            width: h,
                            height: h,
                            color: "text.primary"
                          }
                        }
                      ),
                      onClick: () => {
                        D(e), r.retryConnect = () => {
                          D(e);
                        };
                      },
                      sx: [c === "small" ? { p: 1 } : { p: 2 }]
                    },
                    e.provider
                  )) : null,
                  O ? /* @__PURE__ */ i(
                    he,
                    {
                      ref: _,
                      onSuccess: b,
                      onError: M,
                      tokenState: t,
                      behavior: j,
                      sx: [c === "small" ? { p: 1 } : { p: 2 }],
                      onClick: () => {
                        localStorage.setItem(u, s.PASSKEY);
                        const e = _.current.connect;
                        r.chooseMethod = "passkey", r.retryConnect = () => {
                          R.verifying = !0, r.chooseMethod = "passkey", e();
                        };
                      },
                      slotProps: {
                        icon: {
                          sx: {
                            fontSize: h,
                            "& svg": {
                              fontSize: h,
                              width: "1em",
                              height: "1em"
                            }
                          }
                        }
                      }
                    }
                  ) : null
                ]
              }
            ) : null,
            Z.map((e) => e || null)
          ]
        }
      )
    }
  ) });
}
Ie.propTypes = {
  onSuccess: o.func,
  onError: o.func,
  size: o.oneOf(["small", "normal", "large"]),
  tokenState: o.object.isRequired,
  webWalletUrl: o.string,
  tokenKey: o.string.isRequired,
  passkeyBehavior: o.oneOf(["none", "both", "only-existing", "only-new"]),
  onReset: o.func,
  showMobileLogin: o.bool,
  showOAuthLogin: o.bool,
  showPasskeyLogin: o.bool,
  showWebLogin: o.bool,
  showEmailLogin: o.bool,
  oauthProviderList: o.array,
  slotProps: o.object,
  disableSwitchApp: o.bool,
  forceUpdate: o.func,
  magicToken: o.string,
  baseUrl: o.string,
  customItems: o.arrayOf(o.node)
};
export {
  Ie as default
};
