"use client"

import Link from "next/link"
import { useEffect } from "react"
import { useTheme } from "next-themes"
import { Loader2 } from "lucide-react"
import { AuthCard } from "@/components/auth/auth-card"
import { AuthFlowPage } from "@/components/auth/auth-flow-page"
import {
  authentikEnrollmentFlowUrl,
  resolveAuthentikTheme,
} from "@/lib/auth/authentik-user-url"
import { AUTH_FLOW_SLUGS } from "@/lib/auth/auth-flow-slugs"
import { useClientThemeStore } from "@/lib/stores/client-theme-store"
import { useNativeRuntime } from "@/lib/platform"

type SignupPageContentProps = {
  returnTo?: string
}

export function SignupPageContent({ returnTo = "/mail/inbox" }: SignupPageContentProps) {
  const native = useNativeRuntime()
  const themeMode = useClientThemeStore((s) => s.themeMode)
  const { resolvedTheme } = useTheme()
  const authentikTheme = resolveAuthentikTheme(themeMode, resolvedTheme)
  const flowUrl = authentikEnrollmentFlowUrl(authentikTheme)
  const loginHref = `/login?returnTo=${encodeURIComponent(returnTo)}`
  const oidcHref = `/api/auth/login?returnTo=${encodeURIComponent(returnTo)}`

  useEffect(() => {
    if (!native && flowUrl) {
      window.location.replace(flowUrl)
    }
  }, [native, flowUrl])

  if (native) {
    return (
      <AuthFlowPage
        slug={AUTH_FLOW_SLUGS.enrollment}
        defaultTitle="Créer un compte"
        defaultDescription="Choisissez votre identifiant @ultisuite.fr et configurez votre profil."
        successTitle="Compte créé"
        successDescription="Votre compte UltiSpace est prêt. Connectez-vous pour accéder à la suite."
        successActionLabel="Se connecter"
        successHref={oidcHref}
        successExternal
        footer={
          <p className="w-full text-center text-sm text-muted-foreground">
            Déjà un compte ?{" "}
            <Link className="font-medium text-primary underline" href={loginHref}>
              Se connecter
            </Link>
          </p>
        }
      />
    )
  }

  return (
    <AuthCard
      title="Créer un compte"
      description="Redirection vers l'inscription…"
      footer={
        <p className="w-full text-center text-sm text-muted-foreground">
          Déjà un compte ?{" "}
          <Link className="font-medium text-primary underline" href={loginHref}>
            Se connecter
          </Link>
        </p>
      }
    >
      <div className="flex flex-col items-center gap-4 py-8">
        <Loader2 className="size-6 animate-spin text-muted-foreground" aria-hidden />
        <span className="sr-only">Redirection…</span>
        {!flowUrl ? (
          <p className="text-center text-sm text-destructive" role="alert">
            Configuration Authentik indisponible.
          </p>
        ) : null}
      </div>
    </AuthCard>
  )
}
