import { jsxs as l, jsx as o, Fragment as L } from "react/jsx-runtime";
import c from "prop-types";
import { useState as G, useImperativeHandle as N } from "react";
import p from "@emotion/styled";
import { Alert as Y, TextField as j, Stack as J, Box as z, Dialog as Q, DialogTitle as U, DialogContent as X, Button as k, CircularProgress as A, DialogActions as Z } from "@mui/material";
import m from "validator/lib/isEmail";
import { Icon as ee } from "@iconify/react";
import te from "@iconify-icons/material-symbols/passkey-rounded";
import { useMemoizedFn as d } from "ahooks";
import S from "@arcblock/ux/lib/Toast";
import b from "@arcblock/ux/lib/Typography";
import { getCookieOptions as re } from "@arcblock/ux/lib/Util";
import g from "lodash/trim";
import ie from "base64-url";
import w from "js-cookie";
import $ from "lodash/noop";
import { usePasskey as oe } from "./context.js";
import { getWebAuthnErrorMessage as _ } from "../utils.js";
import { VERIFY_CODE_LENGTH as q } from "./constants.js";
function ne({ ref: y, extraParams: C = {}, createMode: D = "connect", action: P, onSuccess: I = $, onError: R = $ }) {
  const { api: E, locale: T, t: i, loginPasskey: V, logoutPasskey: O, passkeyState: e, connectPasskey: W } = oe(), a = D === "register", [F, s] = G(!1), h = window.innerWidth < 600, B = d(() => {
    e.openDialog = !0, e.error = "", e.creatingStatus = "", e.verifyingStatus = "";
    const t = e.email;
    s(t && a ? !m(t) : !1);
  }), u = d(() => {
    e.openDialog = !1, e.error = "", e.creatingStatus = "", e.verifyingStatus = "";
    const t = e.email;
    s(t && a ? !m(t) : !1);
  }), H = d(async (t) => {
    if (t.preventDefault(), a && !m(e.email)) {
      s(!0);
      return;
    }
    s(!1), e.loading = !0;
    try {
      await E.post(`../kyc/email/send?locale=${T}`, { email: e.email }), e.sent = !0, S.success(i("codeSentSuccess"));
    } catch (r) {
      S.error(r.message), document.getElementById("email-input")?.focus();
    } finally {
      e.loading = !1;
    }
  }), K = d(async (t = "") => {
    try {
      e.verifying = !0, e.error = "", t || (e.verifyingStatus = "");
      const r = await V({
        ...C,
        action: P,
        credentialId: t
      }), n = re({ expireInDays: 7 });
      w.remove("connected_did", n), w.remove("connected_pk", n), w.remove("connected_wallet_os", n), e.verifying = !1, r?.sessionToken && (e.verifyingStatus = "succeed", I({ ...r, encrypted: !1 }, (f) => f));
    } catch (r) {
      console.error("Failed to verify passkey", r);
      const n = _(r, i("verifyPasskeyFailed"));
      e.verifying = !1, e.error = n, e.verifyingStatus = "error", await O(), R(new Error(n));
    }
  }), x = d(async () => {
    if (a && !m(e.email)) {
      s(!0);
      return;
    }
    s(!1), e.creating = !0, e.error = "", e.creatingStatus = "";
    try {
      const t = await W({
        ...C,
        action: P,
        purpose: a ? "register" : "connect",
        email: a ? ie.encode(e.email) : ""
      });
      if (!t) {
        e.error = i("cancelAuth"), e.creatingStatus = "error", e.creating = !1, e.verifying = !1, e.verifyingStatus = "";
        return;
      }
      e.creating = !1, e.openDialog = !1, e.creatingStatus = "succeed", D === "connect" ? I({ ...t, encrypted: !1 }, (r) => r) : t?.credentialId && K(t.credentialId);
    } catch (t) {
      console.error("Failed to create passkey", t), e.creating = !1, e.error = _(t, i("createPasskeyFailed")), e.creatingStatus = "error";
    }
  }), v = d(async (t) => {
    t && t.preventDefault(), e.loading = !0;
    try {
      await E.post(`../kyc/email/verify?locale=${T}`, { code: e.code }), e.verified = !0, x();
    } catch (r) {
      S.error(r.message), e.verified = !1, document.getElementById(`code-input-${g(e.code).length - 1}`)?.focus();
    } finally {
      e.loading = !1;
    }
  });
  N(y, () => ({
    open: B,
    close: u,
    handleVerifyCode: v
  }), [B, u, v]);
  const M = () => /* @__PURE__ */ l(L, { children: [
    /* @__PURE__ */ o(k, { onClick: u, sx: { color: "text.secondary" }, children: i("cancel") }),
    a && /* @__PURE__ */ l(
      k,
      {
        variant: "contained",
        onClick: (
          // eslint-disable-next-line no-nested-ternary
          e.verified ? x : e.sent ? v : H
        ),
        disabled: e.verifying || e.creating || !e.email || e.sent && g(e.code).length !== q,
        children: [
          (e.loading || e.creating) && /* @__PURE__ */ o(A, { size: 16, sx: { mr: 1 } }),
          e.verified ? i("createPasskey") : e.sent ? i("verifyButton") : i("sendCodeButton")
        ]
      }
    ),
    !a && /* @__PURE__ */ o(
      k,
      {
        variant: "contained",
        color: "primary",
        onClick: x,
        disabled: e.loading || e.creating || a && (!e.email || !e.verified),
        startIcon: (e.loading || e.creating) && /* @__PURE__ */ o(A, { size: 16, sx: { mr: 1 }, color: "inherit" }),
        children: e.loading || e.creating ? i("creatingPasskey") : i("createPasskey")
      }
    )
  ] });
  return /* @__PURE__ */ l(
    ae,
    {
      open: e.openDialog,
      onClose: u,
      fullWidth: !0,
      maxWidth: "sm",
      fullScreen: h,
      children: [
        /* @__PURE__ */ l(se, { children: [
          /* @__PURE__ */ o(de, { children: /* @__PURE__ */ o(ee, { icon: te, fontSize: 24, color: "initial" }) }),
          i("createPasskey")
        ] }),
        /* @__PURE__ */ l(le, { children: [
          /* @__PURE__ */ o(b, { variant: "body1", children: i("createPasskeyDesc1") }),
          /* @__PURE__ */ o(b, { variant: "body1", children: i("createPasskeyDesc2") }),
          e.error && /* @__PURE__ */ o(Y, { severity: "error", children: e.error }),
          a && /* @__PURE__ */ l(pe, { children: [
            !e.sent && /* @__PURE__ */ o(
              j,
              {
                type: "email",
                id: "email-input",
                size: "medium",
                placeholder: i("emailPlaceholder"),
                sx: { width: "100%", ".MuiFormHelperText-root": { ml: 0 } },
                value: e.email,
                onChange: (t) => {
                  e.email = t.target.value, s(!m(e.email));
                },
                disabled: e.loading || e.creating,
                required: !0,
                error: F,
                helperText: F ? i("emailInvalid") : ""
              }
            ),
            e.sent && !e.verified && /* @__PURE__ */ l(
              J,
              {
                direction: "column",
                sx: {
                  justifyContent: "center",
                  alignItems: "center",
                  mb: 2
                },
                children: [
                  /* @__PURE__ */ o(b, { variant: "body2", children: i("codeSentMessage", { email: e.email }) }),
                  /* @__PURE__ */ o(z, { sx: { width: "100%", display: "flex", justifyContent: "space-between", gap: 2, mt: 0 }, children: Array(q).fill("").map((t, r) => /* @__PURE__ */ o(
                    j,
                    {
                      value: g(e.code[r]) || "",
                      type: "number",
                      margin: "none",
                      onChange: (n) => {
                        const f = e.code.split("");
                        f[r] = n.target.value, e.code = f.join(""), n.target.value && r < 5 && document.getElementById(`code-input-${r + 1}`)?.focus();
                      },
                      onKeyDown: (n) => {
                        n.key === "Backspace" && !g(e.code[r]) && r > 0 && document.getElementById(`code-input-${r - 1}`)?.focus();
                      },
                      disabled: e.loading,
                      required: !0,
                      id: `code-input-${r}`,
                      autoComplete: "off",
                      slotProps: {
                        htmlInput: {
                          maxLength: 1,
                          style: { textAlign: "center", fontSize: "1.5rem" },
                          autoComplete: "off"
                        }
                      }
                    },
                    `code-input-${r}`
                  )) })
                ]
              }
            )
          ] }),
          h && /* @__PURE__ */ o(z, { sx: { display: "flex", justifyContent: "flex-end", alignItems: "center", mt: 2 }, children: M() })
        ] }),
        !h && /* @__PURE__ */ o(ce, { children: M() })
      ]
    }
  );
}
ne.propTypes = {
  extraParams: c.object,
  createMode: c.string,
  action: c.string.isRequired,
  onSuccess: c.func,
  onError: c.func,
  ref: c.any.isRequired
};
const ae = p(Q)`
  .MuiDialog-paper {
    border-radius: 12px;
    max-width: 440px;
  }
`, se = p(U)`
  text-align: center;
  padding: 24px 24px 16px;
  font-size: 20px;
  font-weight: 600;
`, le = p(X)`
  padding: 0 24px;

  .MuiTypography-body1 {
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 16px;
  }

  .MuiTextField-root {
    margin-top: 16px;
    width: 100%;
  }
`, ce = p(Z)`
  text-align: center;
  padding: 16px 24px 24px;

  .MuiButton-root {
    text-transform: none;
    font-size: 14px;
    border-radius: 6px;
    padding: 6px 16px;
  }
`, de = p("div")`
  width: 48px;
  height: 48px;
  margin: 0 auto 16px;
  background-color: #f6f8fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  svg {
    width: 32px;
    height: 32px;
  }
`, pe = p.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  gap: 24px;

  input[type='number']::-webkit-inner-spin-button,
  input[type='number']::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  div.Mui-focused input {
    caret-color: ${(y) => y.theme.palette.primary.main};
  }
`;
export {
  ne as default
};
