"use client"

import { useSearchParams } from "next/navigation"
import { Suspense } from "react"
import { Button } from "@/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
} from "@/components/ui/card"
import { getAuthentikEnrollmentUrl } from "@/lib/auth/oidc-config"
import { cn } from "@/lib/utils"

const LOGIN_CARD_CLASS = cn(
  "w-full gap-4 border-0 bg-transparent px-4 py-6 shadow-none",
  "sm:gap-5 sm:bg-card sm:dark:bg-mail-surface-elevated sm:px-8 sm:py-8",
  "sm:text-card-foreground sm:dark:text-mail-text sm:shadow-none"
)

function LoginContent() {
  const searchParams = useSearchParams()
  const error = searchParams.get("error")
  const returnTo = searchParams.get("returnTo") ?? "/mail/inbox"
  const loginHref = `/api/auth/login?returnTo=${encodeURIComponent(returnTo)}`
  const signupHref = getAuthentikEnrollmentUrl()

  return (
    <div className="flex flex-1 flex-col items-center justify-center px-4">
      <div className="ultimail-login-card-frame mx-auto w-full max-w-sm">
        <Card className={LOGIN_CARD_CLASS}>
        <CardHeader className="gap-4 px-0 text-center sm:px-0">
          <div className="flex flex-col items-center gap-3 py-4">
            <img
              src="/ultisuite-mark.svg"
              alt=""
              width={72}
              height={72}
              draggable={false}
              className="h-16 w-16 select-none"
              aria-hidden
            />
            <span className="text-2xl font-bold tracking-tight">
              Ulti<span className="text-[#4285F4]">Suite</span>
            </span>
          </div>
          <CardDescription>
            Connecte-toi avec ton compte Ulti (Authentik) pour accéder à ta
            suite : mail, drive, contacts et IA.
          </CardDescription>
          {error ? (
            <p className="text-sm text-destructive" role="alert">
              {decodeURIComponent(error)}
            </p>
          ) : null}
        </CardHeader>

        <CardContent className="flex justify-center px-0 sm:px-0">
          <Button asChild size="lg" className="w-full sm:w-auto">
            <a href={loginHref}>Se connecter</a>
          </Button>
        </CardContent>

        <CardFooter className="px-0 sm:px-0">
          <p className="w-full text-center text-sm text-muted-foreground">
            Pas encore de compte ?{" "}
            <a className="font-medium text-primary underline" href={signupHref}>
              Créer un compte
            </a>
          </p>
        </CardFooter>
        </Card>
      </div>
    </div>
  )
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginContent />
    </Suspense>
  )
}
