"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 {
  authentikRecoveryFlowUrl,
  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"

export function ForgotPasswordPageContent() {
  const native = useNativeRuntime()
  const themeMode = useClientThemeStore((s) => s.themeMode)
  const { resolvedTheme } = useTheme()
  const authentikTheme = resolveAuthentikTheme(themeMode, resolvedTheme)
  const flowUrl = authentikRecoveryFlowUrl(authentikTheme)

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

  const loginFooter = (
    <p className="w-full text-center text-sm text-muted-foreground">
      <Link className="font-medium text-primary underline" href="/login">
        Retour à la connexion
      </Link>
    </p>
  )

  if (native) {
    return (
      <AuthFlowPage
        slug={AUTH_FLOW_SLUGS.recovery}
        defaultTitle="Mot de passe oublié"
        defaultDescription="Indiquez votre adresse e-mail pour recevoir un lien de réinitialisation."
        successTitle="E-mail envoyé"
        successDescription="Si un compte existe pour cette adresse, vous recevrez un e-mail avec les instructions."
        successActionLabel="Retour à la connexion"
        successHref="/login"
        footer={loginFooter}
      />
    )
  }

  return (
    <AuthCard
      title="Mot de passe oublié"
      description="Redirection vers la réinitialisation…"
      footer={loginFooter}
    >
      <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>
  )
}
