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

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

export const meta = () => pageTitle("Sign in")

export default function LoginRoute() {
  const navigate = useNavigate()
  const [params] = useSearchParams()
  const session = useSession()
  const brand = useBrand()

  const next = params.get("next") || "/"

  useEffect(() => {
    if (session) navigate(next, { replace: true })
  }, [session, next, navigate])

  // This is an operator console: don't advertise dev seed credentials or a
  // self-serve "Sign up" path in production. Both are dev conveniences.
  const isDev = import.meta.env.DEV

  return (
    <AuthShell>
      <LoginForm
        brand={<AuthBrand />}
        heading={`Sign in to ${brand.name}`}
        subhead={
          isDev
            ? "Use your arcadia credentials. In dev seeds: admin@example.com / AdminP@ssw0rd."
            : "Use your arcadia credentials."
        }
        onSuccess={async ({ tokens, user, twoFactorRequired, twoFactorChallenge }) => {
          if (twoFactorRequired && twoFactorChallenge) {
            navigate(
              `/login/2fa?challenge=${encodeURIComponent(twoFactorChallenge)}&next=${encodeURIComponent(next)}`,
            )
            return
          }
          persistFromArcadiaLogin(tokens, user)
          navigate(next, { replace: true })
        }}
        onForgotPassword={() => navigate("/login/forgot")}
        onSignup={isDev ? () => navigate("/signup") : undefined}
      />
    </AuthShell>
  )
}
