"use client"

import { useState } from "react"
import { Check, Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import type { ApiTokenCreated } from "@/lib/api/types"

export function ApiTokenCreatedDialog({
  created,
  open,
  onOpenChange,
}: {
  created: ApiTokenCreated | null
  open: boolean
  onOpenChange: (open: boolean) => void
}) {
  const [copied, setCopied] = useState(false)

  async function copyToken() {
    if (!created?.token) return
    await navigator.clipboard.writeText(created.token)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>Token créé</DialogTitle>
          <DialogDescription>
            Copiez ce secret maintenant. Il ne sera plus affiché par la suite.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-2">
          <p className="text-sm font-medium">{created?.name}</p>
          <div className="flex items-start gap-2">
            <code className="flex-1 break-all rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs">
              {created?.token}
            </code>
            <Button type="button" variant="outline" size="icon" onClick={copyToken}>
              {copied ? <Check className="size-4" /> : <Copy className="size-4" />}
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            Préfixe visible : <span className="font-mono">{created?.token_prefix}</span>
          </p>
        </div>
        <DialogFooter>
          <Button type="button" onClick={() => onOpenChange(false)}>
            J&apos;ai copié le token
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
