"use client";

import { useEffect, useState } from "react";
import { Eye } from "lucide-react";
import { api } from "@/lib/api";
import { REVEAL_API_KEY } from "@/lib/api-endpoints";
import { extractApiError } from "@/lib/error";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ApiKey, ApiKeyResponse } from "@/lib/types/api-key";
import { ApiKeyCreatedDialog } from "./ApiKeyCreatedDialog";

interface RevealApiKeyDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  apiKey: ApiKey | null;
}

/**
 * Dialog untuk melihat plaintext API key yang sudah tersimpan.
 * Tidak mengubah data (read-only) — fetch dari GET /api-keys/:id/reveal.
 * Tiap reveal tercatat di audit log BE (ip, user agent, user, timestamp).
 */
export function RevealApiKeyDialog({
  open,
  onOpenChange,
  apiKey,
}: RevealApiKeyDialogProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [plainKey, setPlainKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) {
      setPlainKey(null);
      setError(null);
      setIsLoading(false);
    }
  }, [open, apiKey?.id]);

  const handleReveal = async () => {
    if (!apiKey) return;
    setIsLoading(true);
    setError(null);
    try {
      const res = await api.get<ApiKeyResponse>(
        REVEAL_API_KEY(apiKey.id)
      );
      setPlainKey(res.key);
    } catch (err: any) {
      setError(extractApiError(err, "Gagal menampilkan API key."));
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = (nextOpen: boolean) => {
    if (!nextOpen) {
      setPlainKey(null);
    }
    onOpenChange(nextOpen);
  };

  if (!apiKey) return null;

  return (
    <>
      <Dialog open={open && !plainKey} onOpenChange={handleClose}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5" />
              Tampilkan API Key
            </DialogTitle>
            <p className="text-sm text-muted-foreground">
              Aksi ini akan menampilkan plaintext key untuk{" "}
              <strong>{apiKey.name}</strong>. Tiap reveal tercatat di audit log
              (IP, user agent, timestamp) untuk compliance.
            </p>
          </DialogHeader>

          <DialogBody className="space-y-3">
            <div className="rounded-md border border-blue-200 bg-blue-50 p-3 text-sm text-blue-900">
              <strong>Info:</strong> Key tidak berubah dan klien yang
              menggunakan key ini <strong>tetap valid</strong>. Tidak seperti
              Regenerate, operasi ini hanya menampilkan key yang sudah ada.
            </div>
            {error && (
              <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700">
                {error}
              </div>
            )}
            <div className="space-y-1">
              <label className="text-sm font-medium">Key saat ini (masked)</label>
              <code className="block px-3 py-2 bg-slate-50 border border-slate-200 rounded-md font-mono text-xs text-muted-foreground">
                {apiKey.key_masked}
              </code>
            </div>
          </DialogBody>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => handleClose(false)}
              disabled={isLoading}
            >
              Batal
            </Button>
            <Button onClick={handleReveal} disabled={isLoading}>
              {isLoading ? "Memuat..." : "Tampilkan Key"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <ApiKeyCreatedDialog
        open={!!plainKey}
        onOpenChange={(next) => {
          if (!next) {
            setPlainKey(null);
            handleClose(false);
          }
        }}
        title="API Key Berhasil Ditampilkan"
        description={`Plaintext key untuk "${apiKey.name}". Tindakan ini tercatat di audit log — pastikan key disimpan di password manager / tempat aman.`}
        plaintextKey={plainKey ?? ""}
      />
    </>
  );
}
