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

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

export const meta = () => pageTitle("Two-factor verification")

export default function TwoFactorRoute() {
  const [params] = useSearchParams()
  const navigate = useNavigate()
  const challenge = params.get("challenge") ?? ""
  const next = params.get("next") || "/"
  const [mode, setMode] = useState<"totp" | "recovery">("totp")

  if (!challenge) {
    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">Challenge missing</h1>
          <p className="text-muted-foreground">
            This page is only reachable after a sign-in attempt. Start over.
          </p>
          <button
            type="button"
            onClick={() => navigate("/login")}
            className="mt-2 text-xs font-medium text-primary hover:underline"
            data-action="2fa-back-to-login"
          >
            Back to sign in
          </button>
        </div>
      </AuthShell>
    )
  }

  return (
    <AuthShell>
      <TwoFactorChallengeForm
        brand={<AuthBrand />}
        challenge={challenge}
        mode={mode}
        onUseRecoveryCode={mode === "totp" ? () => setMode("recovery") : undefined}
        onBack={
          mode === "recovery"
            ? () => setMode("totp")
            : () => navigate("/login")
        }
        onSuccess={({ tokens, user }) => {
          persistFromArcadiaLogin(tokens, user)
          navigate(next, { replace: true })
        }}
      />
    </AuthShell>
  )
}
