"use client"

import { useCallback, useEffect, useState } from "react"
import { Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"

export type AuthentikEmbedDialogProps = {
  url: string
  title: string
  open: boolean
  onOpenChange: (open: boolean) => void
  description?: string
}

export function AuthentikEmbedDialog({
  url,
  title,
  open,
  onOpenChange,
  description,
}: AuthentikEmbedDialogProps) {
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    if (open) {
      setIsLoading(true)
    }
  }, [open, url])

  const handleIframeLoad = useCallback(() => {
    setIsLoading(false)
  }, [])

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="gap-0 overflow-hidden border-mail-border bg-mail-surface p-0 sm:max-w-2xl dark:bg-mail-surface-elevated"
        showCloseButton
      >
        <DialogHeader className="space-y-1 border-b border-mail-border px-6 py-4 pr-12">
          <DialogTitle className="text-base font-semibold">{title}</DialogTitle>
          {description ? (
            <DialogDescription>{description}</DialogDescription>
          ) : null}
        </DialogHeader>

        <div className="relative bg-mail-surface dark:bg-mail-surface-elevated">
          {isLoading ? (
            <div
              className="absolute inset-0 z-10 flex items-center justify-center bg-mail-surface/80 dark:bg-mail-surface-elevated/80"
              aria-busy="true"
              aria-live="polite"
            >
              <Loader2
                className="size-6 animate-spin text-muted-foreground"
                aria-hidden
              />
              <span className="sr-only">Chargement du portail d&apos;identité…</span>
            </div>
          ) : null}
          <iframe
            key={url}
            src={url}
            title={title}
            referrerPolicy="no-referrer-when-downgrade"
            allow="clipboard-write"
            onLoad={handleIframeLoad}
            className="block w-full rounded-none border-0 bg-mail-surface dark:bg-mail-surface-elevated"
            style={{ height: "min(72vh, 640px)" }}
          />
        </div>

        <DialogFooter className="flex-row items-center justify-between gap-3 border-t border-mail-border px-6 py-3 sm:justify-between">
          <p className="text-xs text-muted-foreground">
            Géré via votre identité UltiSuite
          </p>
          <DialogClose asChild>
            <Button type="button" variant="outline" className="h-8 rounded-full px-4 text-sm">
              Fermer
            </Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
