%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/
Upload File :
Create Path :
Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/pages/KeysPage.tsx

import { useState } from "react";
import { Link } from "react-router-dom";
import Button from "@/components/ui/Button";
import Card, { CardBody, CardHeader } from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Input from "@/components/ui/Input";
import Modal from "@/components/ui/Modal";
import { useKeys, KEYS_PAGE_SIZE } from "@/hooks/useKeys";
import { formatCredit, formatDate } from "@/lib/format";
import type { ApiKey, CreatedApiKey } from "@/types/api";

export default function KeysPage() {
  const {
    keys,
    total,
    page,
    totalPages,
    setPage,
    loading,
    error,
    createKey,
    revokeKey,
    removePermanent,
  } = useKeys();

  const [createOpen, setCreateOpen] = useState(false);
  const [newName, setNewName] = useState("");
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState<string | null>(null);

  const [createdKey, setCreatedKey] = useState<CreatedApiKey | null>(null);
  const [copied, setCopied] = useState(false);

  const [revokeTarget, setRevokeTarget] = useState<number | null>(null);
  const [revoking, setRevoking] = useState(false);

  // Hapus key permanen
  const [delTarget, setDelTarget] = useState<ApiKey | null>(null);
  const [delConfirm, setDelConfirm] = useState("");
  const [delBusy, setDelBusy] = useState(false);
  const [delError, setDelError] = useState<string | null>(null);

  const openDelete = (key: ApiKey) => {
    setDelTarget(key);
    setDelConfirm("");
    setDelError(null);
  };

  const handleDelete = async () => {
    if (!delTarget) return;
    setDelBusy(true);
    setDelError(null);
    try {
      await removePermanent(delTarget.id);
      setDelTarget(null);
      setDelConfirm("");
      // Jika halaman terakhir jadi kosong setelah hapus, mundur satu halaman.
      if (keys.length === 1 && page > 1) setPage(page - 1);
    } catch (e) {
      setDelError(e instanceof Error ? e.message : "Gagal menghapus key");
      setDelBusy(false);
    }
  };

  const handleCreate = async () => {
    const name = newName.trim();
    if (!name) {
      setCreateError("Nama key wajib diisi.");
      return;
    }
    setCreating(true);
    setCreateError(null);
    try {
      const key = await createKey(name);
      setCreateOpen(false);
      setNewName("");
      setCreatedKey(key);
      setCopied(false);
    } catch (e) {
      setCreateError(e instanceof Error ? e.message : "Gagal membuat key");
    } finally {
      setCreating(false);
    }
  };

  const copyKey = async () => {
    if (!createdKey?.key) return;
    try {
      await navigator.clipboard.writeText(createdKey.key);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      /* clipboard tidak tersedia — biarkan user menyalin manual */
    }
  };

  const handleRevoke = async () => {
    if (revokeTarget == null) return;
    setRevoking(true);
    try {
      await revokeKey(revokeTarget);
      setRevokeTarget(null);
    } catch (e) {
      alert(e instanceof Error ? e.message : "Gagal revoke key");
    } finally {
      setRevoking(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold tracking-tight text-white sm:text-2xl">
            API Keys
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Buat dan kelola kunci API untuk mengakses gateway.
          </p>
        </div>
        <Button onClick={() => setCreateOpen(true)}>
          <svg
            className="h-4 w-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2.2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M12 4.5v15m7.5-7.5h-15"
            />
          </svg>
          Buat Key Baru
        </Button>
      </div>

      <Card>
        <CardHeader
          title="Contoh Pemakaian"
          subtitle="Ringkasan cara memakai API key di gateway"
        />
        <CardBody>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div className="min-w-0 space-y-3">
              <p className="text-xs leading-relaxed text-slate-500">
                Gunakan API key sebagai Bearer token pada header{" "}
                <code className="rounded bg-white/[0.06] px-1.5 py-0.5 font-mono text-[11px] text-brand-200">
                  Authorization
                </code>{" "}
                ke endpoint chat completions.
              </p>
              <div className="inline-flex flex-wrap items-center gap-2 rounded-xl border border-white/[0.06] bg-ink-950/80 px-3 py-2">
                <span className="inline-flex items-center rounded-md border border-blue-400/25 bg-blue-500/10 px-1.5 py-0.5 text-[10px] font-bold tracking-wide text-blue-300">
                  POST
                </span>
                <code className="font-mono text-[11px] text-white">
                  /v1/chat/completions
                </code>
                <span className="text-[10px] text-slate-600">·</span>
                <code className="font-mono text-[10px] text-slate-500">
                  https://api.rezakurnia.com/v1
                </code>
              </div>
              <div className="flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-slate-500">
                <span>
                  • <span className="text-red-300">401</span> key salah /
                  nonaktif
                </span>
                <span>
                  • <span className="text-amber-300">402</span> saldo / kuota
                  habis
                </span>
                <span>
                  • <span className="text-emerald-300">200</span> sukses
                </span>
              </div>
            </div>
            <Link
              to="/docs"
              className="inline-flex shrink-0 items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-blue-500 to-blue-600 px-4 py-2.5 text-xs font-semibold text-white transition-all hover:from-blue-400 hover:to-blue-500 active:scale-[0.98]"
            >
              Buka API Documentation
              <svg
                className="h-3.5 w-3.5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M13.5 4.5L21 12l-7.5 7.5M21 12H3"
                />
              </svg>
            </Link>
          </div>
        </CardBody>
      </Card>

      <Card>
        <CardHeader
          title="Daftar API Key"
          subtitle="Key lengkap hanya terlihat satu kali saat dibuat"
        />
        <CardBody className="p-0">
          {error && (
            <div className="p-5 text-sm text-red-300">
              Gagal memuat key: {error}
            </div>
          )}

          {loading && !error && (
            <div className="space-y-3 p-5">
              {[...Array(3)].map((_, i) => (
                <div
                  key={i}
                  className="h-16 animate-pulse rounded-xl bg-white/[0.02]"
                />
              ))}
            </div>
          )}

          {!loading && !error && keys.length === 0 && (
            <div className="px-5 py-12 text-center">
              <p className="text-sm text-slate-400">Belum ada API key.</p>
              <p className="mt-1 text-xs text-slate-500">
                Buat key pertama Anda untuk mulai memanggil model AI.
              </p>
            </div>
          )}

          {!loading && !error && keys.length > 0 && (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[680px] text-left text-sm">
                <thead>
                  <tr className="border-b border-white/[0.06] bg-white/[0.02] text-[11px] uppercase tracking-wider text-slate-500">
                    <th className="px-5 py-3 font-semibold">Nama</th>
                    <th className="px-4 py-3 font-semibold">Key Prefix</th>
                    <th className="px-4 py-3 font-semibold">Status</th>
                    <th className="px-4 py-3 text-right font-semibold">
                      Saldo Kredit
                    </th>
                    <th className="px-4 py-3 font-semibold">Dibuat</th>
                    <th className="px-5 py-3 text-right font-semibold">
                      Aksi
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {keys.map((key) => {
                    const active = key.is_active === 1;
                    return (
                      <tr
                        key={key.id}
                        className="border-b border-white/[0.04] transition-colors last:border-0 hover:bg-white/[0.02]"
                      >
                        <td className="px-5 py-3.5">
                          <p className="font-medium text-white">{key.name}</p>
                        </td>
                        <td className="px-4 py-3.5">
                          <span className="font-mono text-xs text-slate-500">
                            {key.key_prefix}
                          </span>
                        </td>
                        <td className="px-4 py-3.5">
                          {active ? (
                            <Badge tone="success">
                              <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
                              Aktif
                            </Badge>
                          ) : (
                            <Badge tone="danger">
                              <span className="h-1.5 w-1.5 rounded-full bg-red-400" />
                              Nonaktif
                            </Badge>
                          )}
                        </td>
                        <td className="px-4 py-3.5 text-right font-medium tabular-nums text-slate-300">
                          {formatCredit(key.credit_balance)}
                        </td>
                        <td className="px-4 py-3.5 text-xs tabular-nums text-slate-500">
                          {formatDate(key.created_at)}
                        </td>
                        <td className="px-5 py-3.5 text-right">
                          <div className="flex items-center justify-end gap-2">
                            {active ? (
                              <Button
                                variant="danger"
                                size="sm"
                                onClick={() => setRevokeTarget(key.id)}
                              >
                                Revoke
                              </Button>
                            ) : (
                              <span className="text-xs text-slate-600">—</span>
                            )}
                            <Button
                              variant="subtle"
                              size="sm"
                              title="Hapus key permanen dari akun"
                              onClick={() => openDelete(key)}
                              className="text-red-400 hover:bg-red-500/10 hover:text-red-300"
                            >
                              Hapus
                            </Button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </CardBody>
      </Card>

      {total > KEYS_PAGE_SIZE && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-500">
            Total {total} key · Halaman {page} dari {totalPages}
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              disabled={page <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
            >
              ← Sebelumnya
            </Button>
            <Button
              variant="ghost"
              size="sm"
              disabled={page >= totalPages}
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            >
              Berikutnya →
            </Button>
          </div>
        </div>
      )}

      {/* Modal: buat key */}
      <Modal
        open={createOpen}
        onClose={() => setCreateOpen(false)}
        title="Buat API Key Baru"
        subtitle="Beri nama yang jelas, mis. 'App Mobile' atau 'Server Prod'"
      >
        <div className="space-y-4">
          {createError && (
            <div className="rounded-xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-sm text-red-300">
              {createError}
            </div>
          )}
          <Input
            label="Nama Key"
            placeholder="cth: App Mobile"
            maxLength={100}
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                handleCreate();
              }
            }}
            autoFocus
          />
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setCreateOpen(false)}>
              Batal
            </Button>
            <Button isLoading={creating} onClick={handleCreate}>
              Buat Key
            </Button>
          </div>
        </div>
      </Modal>

      {/* Modal: key baru (hanya muncul sekali) */}
      <Modal
        open={Boolean(createdKey)}
        onClose={() => setCreatedKey(null)}
        title="API Key Berhasil Dibuat 🎉"
        subtitle="Salin sekarang — key tidak akan tampil lagi setelah ditutup."
      >
        <div className="space-y-4">
          <div className="rounded-xl border border-amber-400/25 bg-amber-500/10 px-4 py-3 text-xs text-amber-200">
            ⚠️ Key lengkap hanya ditampilkan sekali. Simpan di tempat aman
            sebelum menutup jendela ini.
          </div>

          <div className="relative">
            <div className="rounded-xl border border-white/[0.08] bg-ink-950/80 px-4 py-3 pr-24 font-mono text-xs text-brand-200 break-all">
              {createdKey?.key}
            </div>
            <button
              onClick={copyKey}
              className="absolute right-2 top-1/2 -translate-y-1/2 rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-xs font-medium text-white transition hover:bg-white/[0.08]"
            >
              {copied ? "✓ Tersalin" : "Salin"}
            </button>
          </div>

          <div className="flex items-center justify-between text-xs text-slate-500">
            <span className="font-mono">{createdKey?.key_prefix}</span>
            <span>
              Saldo:{" "}
              <span className="tabular-nums">
                {createdKey ? formatCredit(createdKey.credit_balance) : "0.00"}
              </span>
            </span>
          </div>

          <Button className="w-full" onClick={() => setCreatedKey(null)}>
            Saya sudah menyimpannya
          </Button>
        </div>
      </Modal>

      {/* Modal: hapus key permanen */}
      <Modal
        open={Boolean(delTarget)}
        onClose={() => {
          if (!delBusy) setDelTarget(null);
        }}
        title="Hapus API Key Permanen"
        subtitle="Tindakan ini tidak dapat dibatalkan"
        width="max-w-sm"
      >
        <div className="space-y-4">
          <div className="rounded-xl border border-red-500/25 bg-red-500/10 px-4 py-3 text-xs leading-relaxed text-red-300">
            Anda akan <strong>menghapus permanen</strong> key{" "}
            <strong>{delTarget?.name}</strong> (
            <span className="font-mono">{delTarget?.key_prefix}…</span>). Key
            ini berhenti berfungsi dan riwayat pemakaiannya ikut terhapus.
          </div>
          <Input
            label={`Ketik nama key untuk konfirmasi: ${delTarget?.name ?? ""}`}
            value={delConfirm}
            onChange={(e) => {
              setDelConfirm(e.target.value);
              setDelError(null);
            }}
            placeholder={delTarget?.name ?? ""}
            autoFocus
          />
          {delError && (
            <p className="text-xs font-medium text-red-400">{delError}</p>
          )}
          <div className="flex justify-end gap-2">
            <Button
              variant="ghost"
              onClick={() => setDelTarget(null)}
              disabled={delBusy}
            >
              Batal
            </Button>
            <Button
              variant="danger"
              isLoading={delBusy}
              disabled={delConfirm.trim() !== delTarget?.name}
              onClick={handleDelete}
            >
              Ya, Hapus
            </Button>
          </div>
          {delConfirm.trim() !== delTarget?.name && (
            <p className="text-right text-[11px] text-slate-500">
              Ketik nama key lengkap untuk mengaktifkan tombol.
            </p>
          )}
        </div>
      </Modal>

      {/* Modal: konfirmasi revoke */}
      <Modal
        open={revokeTarget != null}
        onClose={() => setRevokeTarget(null)}
        title="Revoke API Key?"
        subtitle="Key akan langsung nonaktif dan tidak bisa dipakai lagi."
        width="max-w-sm"
      >
        <div className="space-y-4">
          <p className="text-sm text-slate-400">
            Tindakan ini tidak bisa dibatalkan. Key yang di-revoke tetap tampil
            di daftar dengan status Nonaktif.
          </p>
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setRevokeTarget(null)}>
              Batal
            </Button>
            <Button
              variant="danger"
              isLoading={revoking}
              onClick={handleRevoke}
            >
              Ya, Revoke
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

Zerion Mini Shell 1.0