"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { PasswordInput } from "@open-mercato/ui/primitives/password-input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Button } from "@open-mercato/ui/primitives/button";
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
import { SearchX } from "lucide-react";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { usePortalContext } from "@open-mercato/ui/portal/PortalContext";
import { InjectionSpot } from "@open-mercato/ui/backend/injection/InjectionSpot";
import { PortalInjectionSpots } from "@open-mercato/ui/backend/injection/spotIds";
function PortalResetPasswordPage({ params }) {
  const t = useT();
  const orgSlug = params.orgSlug;
  const { tenant } = usePortalContext();
  const searchParams = useSearchParams();
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [token, setToken] = useState(null);
  useEffect(() => {
    const tokenParam = searchParams.get("token");
    if (!tokenParam) {
      setError(t("portal.resetPassword.error.noToken", "Invalid or missing reset token."));
    } else {
      setToken(tokenParam);
    }
  }, [searchParams, t]);
  const handleSubmit = useCallback(
    async (event) => {
      event.preventDefault();
      setError(null);
      if (!token) {
        setError(t("portal.resetPassword.error.noToken", "Invalid or missing reset token."));
        return;
      }
      if (password !== confirmPassword) {
        setError(t("portal.resetPassword.error.passwordMismatch", "Passwords do not match."));
        return;
      }
      if (password.length < 8) {
        setError(t("portal.resetPassword.error.passwordTooShort", "Password must be at least 8 characters long."));
        return;
      }
      setSubmitting(true);
      try {
        const result = await apiCall("/api/customer_accounts/password/reset-confirm", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token, password })
        });
        if (result.ok && result.result?.ok) {
          setSuccess(true);
          return;
        }
        if (result.status === 400) {
          setError(t("portal.resetPassword.error.invalidToken", "Invalid or expired reset token."));
        } else {
          setError(result.result?.error || t("portal.resetPassword.error.generic", "Password reset failed. Please try again."));
        }
      } catch {
        setError(t("portal.resetPassword.error.generic", "Password reset failed. Please try again."));
      } finally {
        setSubmitting(false);
      }
    },
    [token, password, confirmPassword, t]
  );
  const injectionContext = useMemo(
    () => ({ orgSlug }),
    [orgSlug]
  );
  if (tenant.loading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-20", children: /* @__PURE__ */ jsx(Spinner, {}) });
  }
  if (tenant.error) {
    return /* @__PURE__ */ jsx("div", { className: "mx-auto w-full max-w-md py-12", children: /* @__PURE__ */ jsx(
      EmptyState,
      {
        variant: "subtle",
        size: "lg",
        icon: /* @__PURE__ */ jsx(SearchX, { className: "h-6 w-6", "aria-hidden": true }),
        title: t("portal.org.invalid", "Organization not found.")
      }
    ) });
  }
  if (success) {
    return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "mb-8 text-center", children: [
        /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.resetPassword.success.title", "Password Reset Complete") }),
        /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.resetPassword.success.description", "Your password has been successfully reset.") })
      ] }),
      /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: t("portal.resetPassword.success.message", "You can now sign in with your new password.") }) }),
      /* @__PURE__ */ jsx("div", { className: "mt-6 text-center", children: /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.resetPassword.success.loginLink", "Go to Sign In") }) })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-8 text-center", children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.resetPassword.title", "Reset Password") }),
      /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.resetPassword.description", "Enter your new password below.") })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageBefore("reset-password"), context: injectionContext }),
    /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "flex flex-col gap-4", children: [
      error ? /* @__PURE__ */ jsx(Alert, { variant: "destructive", children: /* @__PURE__ */ jsx(AlertDescription, { children: error }) }) : null,
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "reset-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.resetPassword.password", "New Password") }),
        /* @__PURE__ */ jsx(PasswordInput, { id: "reset-password", autoComplete: "new-password", required: true, placeholder: t("portal.resetPassword.password.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: password, onChange: (e) => setPassword(e.target.value), disabled: submitting || !token, className: "rounded-lg" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "confirm-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.resetPassword.confirmPassword", "Confirm New Password") }),
        /* @__PURE__ */ jsx(PasswordInput, { id: "confirm-password", autoComplete: "new-password", required: true, placeholder: t("portal.resetPassword.confirmPassword.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), disabled: submitting || !token, className: "rounded-lg" })
      ] }),
      /* @__PURE__ */ jsx(Button, { type: "submit", disabled: submitting || !token, className: "mt-1 w-full rounded-lg", children: submitting ? t("portal.resetPassword.submitting", "Resetting password...") : t("portal.resetPassword.submit", "Reset Password") }),
      /* @__PURE__ */ jsxs("p", { className: "text-center text-sm text-muted-foreground", children: [
        t("portal.resetPassword.backToLogin", "Remember your password?"),
        " ",
        /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.resetPassword.loginLink", "Sign in") })
      ] })
    ] }),
    /* @__PURE__ */ jsx(InjectionSpot, { spotId: PortalInjectionSpots.pageAfter("reset-password"), context: injectionContext })
  ] });
}
export {
  PortalResetPasswordPage as default
};
//# sourceMappingURL=page.js.map
