import { useNavigate, useSearchParams } from "react-router"

import { PasswordResetConfirmForm } from "@crema/arcadia-auth-ui"
import { pageTitle } from "~/lib/page-meta"
import { AuthBrand, AuthShell } from "~/components/auth/auth-shell"

export const meta = () => pageTitle("Set new password")

export default function ResetPasswordRoute() {
  const [params] = useSearchParams()
  const navigate = useNavigate()
  const token = params.get("token") ?? ""

  if (!token) {
    return (
      <AuthShell>
        <div
          className="flex w-full max-w-sm flex-col items-center gap-3 rounded-xl border bg-card p-6 text-center text-sm"
          style={{ borderColor: "var(--border)" }}
        >
          <h1 className="text-base font-semibold">Reset link invalid</h1>
          <p className="text-muted-foreground">
            No token in the URL. Request a fresh password reset email.
          </p>
          <button
            type="button"
            onClick={() => navigate("/login/forgot")}
            className="mt-2 text-xs font-medium text-primary hover:underline"
            data-action="reset-request-new"
          >
            Request a new link
          </button>
        </div>
      </AuthShell>
    )
  }

  return (
    <AuthShell>
      <PasswordResetConfirmForm
        brand={<AuthBrand />}
        token={token}
        onSuccess={() => navigate("/login?reset=ok", { replace: true })}
      />
    </AuthShell>
  )
}
