import {
  AvatarBox
} from "./chunk-CP5IL4P6.js";
import "./chunk-U2EI2ZLM.js";
import "./chunk-FMFVTERD.js";
import {
  i18n
} from "./chunk-ZMDE5HEV.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useResetPasswordForEmailPass,
  useUpdateProviderForEmailPass
} from "./chunk-MFL2TZ3W.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/reset-password/reset-password.tsx
import { useState } from "react";
import { Alert, Button, Heading, Input, Text, toast } from "@medusajs/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
import { decodeToken } from "react-jwt";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import * as z from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var ResetPasswordInstructionsSchema = z.object({
  email: z.string().email()
});
var ResetPasswordSchema = z.object({
  password: z.string().min(1),
  repeat_password: z.string().min(1)
}).superRefine(({ password, repeat_password }, ctx) => {
  if (password !== repeat_password) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: i18n.t("resetPassword.passwordMismatch"),
      path: ["repeat_password"]
    });
  }
});
var ResetPasswordTokenSchema = z.object({
  entity_id: z.string(),
  provider: z.string(),
  exp: z.number(),
  iat: z.number()
});
var validateDecodedResetPasswordToken = (decoded) => {
  return ResetPasswordTokenSchema.safeParse(decoded).success;
};
var InvalidResetToken = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex min-h-dvh w-dvw items-center justify-center bg-ui-bg-base",
      "data-testid": "reset-password-invalid-token-page",
      children: /* @__PURE__ */ jsxs(
        "div",
        {
          className: "m-4 flex w-full max-w-[300px] flex-col items-center",
          "data-testid": "reset-password-invalid-token-container",
          children: [
            /* @__PURE__ */ jsx(AvatarBox, {}),
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: "mb-6 flex flex-col items-center",
                "data-testid": "reset-password-invalid-token-header",
                children: [
                  /* @__PURE__ */ jsx(Heading, { "data-testid": "reset-password-invalid-token-title", children: t("resetPassword.invalidLinkTitle") }),
                  /* @__PURE__ */ jsx(
                    Text,
                    {
                      size: "small",
                      className: "text-center text-ui-fg-subtle",
                      "data-testid": "reset-password-invalid-token-hint",
                      children: t("resetPassword.invalidLinkHint")
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsx("div", { className: "flex w-full flex-col gap-y-3", children: /* @__PURE__ */ jsx(
              Button,
              {
                onClick: () => navigate("/reset-password", { replace: true }),
                className: "w-full",
                type: "submit",
                "data-testid": "reset-password-invalid-token-button",
                children: t("resetPassword.goToResetPassword")
              }
            ) }),
            /* @__PURE__ */ jsx(
              "span",
              {
                className: "txt-small my-6",
                "data-testid": "reset-password-invalid-token-back-to-login-section",
                children: /* @__PURE__ */ jsx(
                  Trans,
                  {
                    i18nKey: "resetPassword.backToLogin",
                    components: [
                      /* @__PURE__ */ jsx(
                        Link,
                        {
                          to: "/login",
                          className: "text-ui-fg-interactive outline-none transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover",
                          "data-testid": "reset-password-invalid-token-back-to-login-link"
                        },
                        "login-link"
                      )
                    ]
                  }
                )
              }
            )
          ]
        }
      )
    }
  );
};
var ChooseNewPassword = ({ token }) => {
  const { t } = useTranslation();
  const [showAlert, setShowAlert] = useState(false);
  const invite = token ? decodeToken(token) : null;
  const isValidResetPasswordToken = invite && validateDecodedResetPasswordToken(invite);
  const form = useForm({
    resolver: zodResolver(ResetPasswordSchema),
    defaultValues: {
      password: "",
      repeat_password: ""
    }
  });
  const { mutateAsync, isPending } = useUpdateProviderForEmailPass(token);
  const handleSubmit = form.handleSubmit(async ({ password }) => {
    if (!invite) {
      return;
    }
    await mutateAsync(
      {
        password
      },
      {
        onSuccess: () => {
          form.setValue("password", "");
          form.setValue("repeat_password", "");
          setShowAlert(true);
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  if (!isValidResetPasswordToken) {
    return /* @__PURE__ */ jsx(InvalidResetToken, {});
  }
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex min-h-dvh w-dvw items-center justify-center bg-ui-bg-subtle",
      "data-testid": "reset-password-choose-new-password-page",
      children: /* @__PURE__ */ jsxs(
        "div",
        {
          className: "m-4 flex w-full max-w-[280px] flex-col items-center",
          "data-testid": "reset-password-choose-new-password-container",
          children: [
            /* @__PURE__ */ jsx(AvatarBox, {}),
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: "mb-6 flex flex-col items-center",
                "data-testid": "reset-password-choose-new-password-header",
                children: [
                  /* @__PURE__ */ jsx(Heading, { "data-testid": "reset-password-choose-new-password-title", children: t("resetPassword.resetPassword") }),
                  /* @__PURE__ */ jsx(
                    Text,
                    {
                      size: "small",
                      className: "text-center text-ui-fg-subtle",
                      "data-testid": "reset-password-choose-new-password-hint",
                      children: t("resetPassword.newPasswordHint")
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsx("div", { className: "flex w-full flex-col gap-y-3", children: /* @__PURE__ */ jsx(Form, { ...form, children: /* @__PURE__ */ jsxs(
              "form",
              {
                onSubmit: handleSubmit,
                className: "flex w-full flex-col gap-y-6",
                "data-testid": "reset-password-choose-new-password-form",
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        type: "email",
                        disabled: true,
                        value: invite?.entity_id,
                        "data-testid": "reset-password-email-display"
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "password",
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { children: [
                            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                              Input,
                              {
                                autoComplete: "new-password",
                                type: "password",
                                ...field,
                                placeholder: t("resetPassword.newPassword"),
                                "data-testid": "reset-password-new-password-input"
                              }
                            ) }),
                            /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                          ] });
                        }
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "repeat_password",
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { children: [
                            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                              Input,
                              {
                                autoComplete: "off",
                                type: "password",
                                ...field,
                                placeholder: t("resetPassword.repeatNewPassword"),
                                "data-testid": "reset-password-repeat-password-input"
                              }
                            ) }),
                            /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                          ] });
                        }
                      }
                    )
                  ] }),
                  showAlert && /* @__PURE__ */ jsx(
                    Alert,
                    {
                      dismissible: true,
                      variant: "success",
                      "data-testid": "reset-password-success-alert",
                      children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                        /* @__PURE__ */ jsx("span", { className: "mb-1 text-ui-fg-base", children: t("resetPassword.successfulResetTitle") }),
                        /* @__PURE__ */ jsx("span", { children: t("resetPassword.successfulReset") })
                      ] })
                    }
                  ),
                  !showAlert && /* @__PURE__ */ jsx(
                    Button,
                    {
                      className: "w-full",
                      type: "submit",
                      isLoading: isPending,
                      "data-testid": "reset-password-submit-button",
                      children: t("resetPassword.resetPassword")
                    }
                  )
                ]
              }
            ) }) }),
            /* @__PURE__ */ jsx(
              "span",
              {
                className: "txt-small my-6",
                "data-testid": "reset-password-choose-new-password-back-to-login-section",
                children: /* @__PURE__ */ jsx(
                  Trans,
                  {
                    i18nKey: "resetPassword.backToLogin",
                    components: [
                      /* @__PURE__ */ jsx(
                        Link,
                        {
                          to: "/login",
                          className: "hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover text-ui-fg-base outline-none transition-fg",
                          "data-testid": "reset-password-choose-new-password-back-to-login-link"
                        },
                        "login-link"
                      )
                    ]
                  }
                )
              }
            )
          ]
        }
      )
    }
  );
};
var ResetPassword = () => {
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const [showAlert, setShowAlert] = useState(false);
  const token = searchParams.get("token");
  const form = useForm({
    resolver: zodResolver(ResetPasswordInstructionsSchema),
    defaultValues: {
      email: ""
    }
  });
  const { mutateAsync, isPending } = useResetPasswordForEmailPass();
  const handleSubmit = form.handleSubmit(async ({ email }) => {
    await mutateAsync(
      {
        email
      },
      {
        onSuccess: () => {
          form.setValue("email", "");
          setShowAlert(true);
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  if (token) {
    return /* @__PURE__ */ jsx(ChooseNewPassword, { token });
  }
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex min-h-dvh w-dvw items-center justify-center bg-ui-bg-base",
      "data-testid": "reset-password-page",
      children: /* @__PURE__ */ jsxs(
        "div",
        {
          className: "m-4 flex w-full max-w-[300px] flex-col items-center",
          "data-testid": "reset-password-container",
          children: [
            /* @__PURE__ */ jsx(AvatarBox, {}),
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: "mb-4 flex flex-col items-center",
                "data-testid": "reset-password-header",
                children: [
                  /* @__PURE__ */ jsx(Heading, { "data-testid": "reset-password-title", children: t("resetPassword.resetPassword") }),
                  /* @__PURE__ */ jsx(
                    Text,
                    {
                      size: "small",
                      className: "text-center text-ui-fg-subtle",
                      "data-testid": "reset-password-hint",
                      children: t("resetPassword.hint")
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsx("div", { className: "flex w-full flex-col gap-y-3", children: /* @__PURE__ */ jsx(Form, { ...form, children: /* @__PURE__ */ jsxs(
              "form",
              {
                onSubmit: handleSubmit,
                className: "flex w-full flex-col gap-y-6",
                "data-testid": "reset-password-form",
                children: [
                  /* @__PURE__ */ jsx("div", { className: "mt-4 flex flex-col gap-y-3", children: /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: "email",
                      render: ({ field }) => {
                        return /* @__PURE__ */ jsxs(Form.Item, { children: [
                          /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              autoComplete: "email",
                              ...field,
                              placeholder: t("fields.email"),
                              "data-testid": "reset-password-email-input"
                            }
                          ) }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                        ] });
                      }
                    }
                  ) }),
                  showAlert && /* @__PURE__ */ jsx(
                    Alert,
                    {
                      dismissible: true,
                      variant: "success",
                      "data-testid": "reset-password-success-alert",
                      children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                        /* @__PURE__ */ jsx("span", { className: "mb-1 text-ui-fg-base", children: t("resetPassword.successfulRequestTitle") }),
                        /* @__PURE__ */ jsx("span", { children: t("resetPassword.successfulRequest") })
                      ] })
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      className: "w-full",
                      type: "submit",
                      isLoading: isPending,
                      "data-testid": "reset-password-submit-button",
                      children: t("resetPassword.sendResetInstructions")
                    }
                  )
                ]
              }
            ) }) }),
            /* @__PURE__ */ jsx(
              "span",
              {
                className: "txt-small my-6",
                "data-testid": "reset-password-back-to-login-section",
                children: /* @__PURE__ */ jsx(
                  Trans,
                  {
                    i18nKey: "resetPassword.backToLogin",
                    components: [
                      /* @__PURE__ */ jsx(
                        Link,
                        {
                          to: "/login",
                          className: "hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover text-ui-fg-base outline-none transition-fg",
                          "data-testid": "reset-password-back-to-login-link"
                        },
                        "login-link"
                      )
                    ]
                  }
                )
              }
            )
          ]
        }
      )
    }
  );
};
export {
  ResetPassword as Component
};
