/**
 * <SecretsSection /> — renders the registered secrets from the framework
 * secrets registry. Configured keys stay compact; adding or editing one
 * progressively discloses its controls.
 */

import { Picker, TextField } from "@agent-native/toolkit/design-system";
import {
  Button as ToolkitButton,
  ButtonBase as ToolkitButtonBase,
} from "@agent-native/toolkit/ui/button";
import {
  IconCheck,
  IconChevronRight,
  IconExternalLink,
  IconLoader2,
  IconPlugConnected,
  IconPlus,
  IconTrash,
  IconRefresh,
} from "@tabler/icons-react";
import React, { useEffect, useMemo, useState, useCallback } from "react";

import { agentNativePath } from "../api-path.js";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "../components/ui/dropdown-menu.js";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "../components/ui/tooltip.js";
import { useT } from "../i18n.js";
import { cn } from "../utils.js";

const Button = React.forwardRef<
  HTMLButtonElement,
  React.ComponentPropsWithoutRef<typeof ToolkitButton>
>(({ className, ...props }, ref) => (
  <ToolkitButton
    ref={ref}
    variant="ghost"
    className={cn(
      "h-auto p-0 hover:bg-transparent hover:text-inherit active:scale-100 [&_svg]:!size-auto",
      className,
    )}
    {...props}
  />
));
Button.displayName = "SecretsPrimitiveButton";

interface SecretStatus {
  key: string;
  label: string;
  description?: string;
  docsUrl?: string;
  scope: "user" | "workspace";
  kind: "api-key" | "oauth";
  required: boolean;
  status: "set" | "unset" | "invalid";
  last4?: string;
  updatedAt?: number;
  oauthProvider?: string;
  oauthConnectUrl?: string;
  error?: string;
}

const ENDPOINT = agentNativePath("/_agent-native/secrets");

function notifySecretsChanged() {
  if (typeof window === "undefined") return;
  window.dispatchEvent(
    new CustomEvent("agent-engine:configured-changed", {
      detail: { source: "secrets" },
    }),
  );
}

export interface SecretsSectionProps {
  /** Optional hash fragment to focus a specific secret (e.g. "secrets:OPENAI_API_KEY"). */
  focusKey?: string;
}

export function SecretsSection({ focusKey }: SecretsSectionProps) {
  const [secrets, setSecrets] = useState<SecretStatus[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [reloadToken, setReloadToken] = useState(0);
  const [openSecretKey, setOpenSecretKey] = useState<string | null>(
    focusKey ?? null,
  );
  const [customKeyOpen, setCustomKeyOpen] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch(ENDPOINT)
      .then(async (r) => {
        if (!r.ok) {
          throw new Error(`Failed to load secrets (${r.status})`);
        }
        return (await r.json()) as SecretStatus[];
      })
      .then((data) => {
        if (!cancelled) setSecrets(data);
      })
      .catch((err) => {
        if (!cancelled) setError(err?.message ?? "Failed to load");
      });
    return () => {
      cancelled = true;
    };
  }, [reloadToken]);

  const reload = useCallback(() => setReloadToken((t) => t + 1), []);

  useEffect(() => {
    if (focusKey) {
      setCustomKeyOpen(false);
      setOpenSecretKey(focusKey);
    }
  }, [focusKey]);

  if (error) {
    return (
      <p className="text-[10px] text-red-500">
        Failed to load secrets: {error}
      </p>
    );
  }
  if (secrets === null) {
    return (
      <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
        <IconLoader2 size={10} className="animate-spin" />
        Loading…
      </div>
    );
  }
  if (secrets.length === 0) {
    return (
      <div className="space-y-3">
        <KeysHeader onCustomKey={() => setCustomKeyOpen(true)} />
        <AdHocKeysSection
          showForm={customKeyOpen}
          onShowFormChange={setCustomKeyOpen}
          showEmptyState
        />
      </div>
    );
  }

  const visibleSecrets = secrets.filter(
    (secret) => secret.status !== "unset" || secret.key === openSecretKey,
  );
  const availableSecrets = secrets.filter(
    (secret) => secret.status === "unset" && secret.key !== openSecretKey,
  );

  return (
    <div className="space-y-3">
      <KeysHeader
        availableSecrets={availableSecrets}
        onSecret={(key) => {
          setCustomKeyOpen(false);
          setOpenSecretKey(key);
        }}
        onCustomKey={() => {
          setOpenSecretKey(null);
          setCustomKeyOpen(true);
        }}
      />
      {visibleSecrets.length > 0 && (
        <div className="overflow-hidden rounded-md border border-border">
          {visibleSecrets.map((secret) => (
            <SecretCard
              key={secret.key}
              secret={secret}
              onChanged={reload}
              open={openSecretKey === secret.key}
              onOpenChange={(open) => {
                if (open) setCustomKeyOpen(false);
                setOpenSecretKey(open ? secret.key : null);
              }}
              focusInput={openSecretKey === secret.key}
            />
          ))}
        </div>
      )}
      <AdHocKeysSection
        showForm={customKeyOpen}
        onShowFormChange={setCustomKeyOpen}
        showEmptyState={visibleSecrets.length === 0}
      />
    </div>
  );
}

function KeysHeader({
  availableSecrets = [],
  onSecret,
  onCustomKey,
}: {
  availableSecrets?: SecretStatus[];
  onSecret?: (key: string) => void;
  onCustomKey: () => void;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <p className="text-[11px] font-medium text-foreground">Keys</p>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <ToolkitButtonBase
            type="button"
            variant="outline"
            className="inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-[10px] font-medium text-muted-foreground transition-colors hover:bg-accent/40 hover:text-foreground"
          >
            <IconPlus size={11} />
            New
          </ToolkitButtonBase>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-60">
          {availableSecrets.length > 0 && (
            <>
              <DropdownMenuLabel>Choose a key</DropdownMenuLabel>
              {availableSecrets.map((secret) => (
                <DropdownMenuItem
                  key={secret.key}
                  onSelect={() => onSecret?.(secret.key)}
                  className="flex items-center justify-between gap-3"
                >
                  <span className="truncate">{secret.label}</span>
                  {secret.required && (
                    <span className="text-[9px] font-semibold uppercase tracking-wide text-amber-600 dark:text-amber-400">
                      Required
                    </span>
                  )}
                </DropdownMenuItem>
              ))}
              <DropdownMenuSeparator />
            </>
          )}
          <DropdownMenuItem onSelect={onCustomKey}>
            <IconPlus size={14} />
            Custom
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}

interface SecretCardProps {
  secret: SecretStatus;
  onChanged: () => void;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  focusInput?: boolean;
}

function SecretCard({
  secret,
  onChanged,
  open,
  onOpenChange,
  focusInput,
}: SecretCardProps) {
  const [value, setValue] = useState("");
  const [busy, setBusy] = useState<null | "save" | "delete" | "test">(null);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [toast, setToast] = useState<{
    kind: "ok" | "err";
    text: string;
  } | null>(null);
  const inputRef = React.useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (open && focusInput && inputRef.current) {
      inputRef.current.focus();
    }
  }, [focusInput, open]);

  const setToastAndClear = (kind: "ok" | "err", text: string, ms = 2500) => {
    setToast({ kind, text });
    setTimeout(() => setToast(null), ms);
  };

  const handleSave = async () => {
    if (!value.trim() || busy) return;
    setBusy("save");
    try {
      const res = await fetch(`${ENDPOINT}/${encodeURIComponent(secret.key)}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ value: value.trim() }),
      });
      if (!res.ok) {
        const err = await res
          .json()
          .then((j: { error?: string }) => j.error)
          .catch(() => null);
        setToastAndClear("err", err ?? `Save failed (${res.status})`);
        return;
      }
      setValue("");
      setConfirmDelete(false);
      setToastAndClear("ok", "Saved");
      notifySecretsChanged();
      onChanged();
    } finally {
      setBusy(null);
    }
  };

  const handleDelete = async () => {
    if (busy) return;
    setBusy("delete");
    try {
      const res = await fetch(`${ENDPOINT}/${encodeURIComponent(secret.key)}`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
      });
      if (!res.ok) {
        const err = await res
          .json()
          .then((j: { error?: string }) => j.error)
          .catch(() => null);
        setToastAndClear("err", err ?? `Delete failed (${res.status})`);
        return;
      }
      setToastAndClear("ok", "Removed");
      setConfirmDelete(false);
      notifySecretsChanged();
      onChanged();
    } finally {
      setBusy(null);
    }
  };

  const handleTest = async () => {
    if (busy) return;
    setBusy("test");
    try {
      const res = await fetch(
        `${ENDPOINT}/${encodeURIComponent(secret.key)}/test`,
        {
          method: "POST",
        },
      );
      const body = (await res.json().catch(() => ({}))) as {
        ok?: boolean;
        error?: string;
      };
      if (res.ok && body.ok) {
        setToastAndClear("ok", "Working");
      } else {
        setToastAndClear(
          "err",
          body.error ?? (body.ok === false ? "Invalid" : `Test failed`),
        );
      }
    } finally {
      setBusy(null);
    }
  };

  const pill = useMemo(() => {
    if (secret.status === "set") {
      return (
        <span className="flex items-center gap-1 text-[10px] text-green-500">
          <IconCheck size={10} />
          Set
        </span>
      );
    }
    if (secret.required) {
      return (
        <span className="rounded-full bg-red-500/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-red-500">
          Required
        </span>
      );
    }
    return (
      <span className="rounded-full bg-accent/60 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground">
        Optional
      </span>
    );
  }, [secret.status, secret.required]);

  const isOAuth = secret.kind === "oauth";

  return (
    <div className="border-b border-border last:border-b-0">
      <Button
        type="button"
        intent="neutral"
        emphasis="ghost"
        aria-expanded={open}
        onClick={() => onOpenChange(!open)}
        className="flex w-full items-center gap-2 px-2.5 py-2 text-start transition-colors hover:bg-accent/30"
      >
        <IconChevronRight
          size={13}
          className={`shrink-0 text-muted-foreground transition-transform ${open ? "rotate-90" : ""}`}
        />
        <span className="min-w-0 flex-1 truncate text-[11px] font-medium text-foreground">
          {secret.label}
        </span>
        {secret.status === "set" && secret.last4 && (
          <code className="text-[10px] text-muted-foreground">
            ••••{secret.last4}
          </code>
        )}
        <span className="shrink-0">{pill}</span>
      </Button>

      {open && (
        <div className="border-t border-border/60 bg-accent/20 px-3 pb-3 pt-2.5">
          {secret.description && (
            <p className="mb-2 text-[10px] leading-relaxed text-muted-foreground">
              {secret.description}
            </p>
          )}
          {isOAuth ? (
            <div className="mt-2 flex items-center gap-1.5">
              {secret.oauthConnectUrl && (
                <a
                  href={secret.oauthConnectUrl}
                  className="inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium no-underline"
                  style={{ backgroundColor: "#00B5FF", color: "white" }}
                >
                  <IconPlugConnected size={10} />
                  {secret.status === "set" ? "Reconnect" : "Connect"}
                </a>
              )}
              {secret.docsUrl && (
                <a
                  href={secret.docsUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] no-underline text-muted-foreground hover:text-foreground"
                >
                  Docs
                  <IconExternalLink size={10} />
                </a>
              )}
            </div>
          ) : (
            <div className="mt-2 space-y-1.5">
              {secret.status === "set" && (
                <div className="flex items-center gap-2 text-[10px] text-muted-foreground">
                  <span>Stored value ending in</span>
                  <code className="rounded bg-background px-1 py-0.5 text-foreground">
                    {secret.last4}
                  </code>
                </div>
              )}
              <div className="flex gap-1.5">
                <TextField
                  inputRef={inputRef}
                  type="password"
                  aria-label={secret.label}
                  value={value}
                  onChange={setValue}
                  onKeyDown={(event) => {
                    if (event.key === "Enter") handleSave();
                  }}
                  placeholder={
                    secret.status === "set"
                      ? "Enter new value to rotate"
                      : "Paste key"
                  }
                  className="flex-1 text-[11px]"
                />
                <Button
                  type="button"
                  intent="primary"
                  emphasis="solid"
                  onClick={handleSave}
                  disabled={!value.trim() || busy !== null}
                  className="inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium disabled:opacity-40"
                  style={{ backgroundColor: "#00B5FF", color: "white" }}
                >
                  {busy === "save" ? (
                    <IconLoader2 size={10} className="animate-spin" />
                  ) : secret.status === "set" ? (
                    <>
                      <IconRefresh size={10} />
                      Rotate
                    </>
                  ) : (
                    "Save"
                  )}
                </Button>
              </div>
              <div className="flex items-center gap-1.5">
                {secret.status === "set" && (
                  <>
                    <Button
                      type="button"
                      intent="neutral"
                      emphasis="outline"
                      onClick={handleTest}
                      disabled={busy !== null}
                      className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] text-muted-foreground hover:text-foreground disabled:opacity-40"
                    >
                      {busy === "test" ? (
                        <IconLoader2 size={10} className="animate-spin" />
                      ) : (
                        "Test"
                      )}
                    </Button>
                    <Button
                      type="button"
                      intent="danger"
                      emphasis="outline"
                      onClick={() => setConfirmDelete(true)}
                      disabled={busy !== null}
                      className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] text-muted-foreground hover:text-red-500 disabled:opacity-40"
                    >
                      <IconTrash size={10} />
                      Remove
                    </Button>
                  </>
                )}
                {secret.docsUrl && (
                  <a
                    href={secret.docsUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] no-underline text-muted-foreground hover:text-foreground ms-auto"
                  >
                    Get key
                    <IconExternalLink size={10} />
                  </a>
                )}
              </div>
              {confirmDelete && (
                <div className="flex items-center gap-1.5 rounded border border-red-500/30 bg-red-500/10 px-2 py-1.5 text-[10px] text-red-500">
                  <span className="min-w-0 flex-1">
                    Remove this saved value?
                  </span>
                  <Button
                    type="button"
                    intent="danger"
                    emphasis="solid"
                    onClick={handleDelete}
                    disabled={busy !== null}
                    className="inline-flex items-center gap-1 rounded border border-red-500/40 px-1.5 py-0.5 font-medium disabled:opacity-40"
                  >
                    {busy === "delete" ? (
                      <IconLoader2 size={10} className="animate-spin" />
                    ) : (
                      "Confirm"
                    )}
                  </Button>
                  <Button
                    type="button"
                    intent="neutral"
                    emphasis="outline"
                    onClick={() => setConfirmDelete(false)}
                    disabled={busy !== null}
                    className="rounded border border-border px-1.5 py-0.5 text-muted-foreground hover:text-foreground disabled:opacity-40"
                  >
                    Cancel
                  </Button>
                </div>
              )}
            </div>
          )}

          {toast && (
            <p
              className={`mt-1.5 text-[10px] ${
                toast.kind === "ok" ? "text-green-500" : "text-red-500"
              }`}
            >
              {toast.text}
            </p>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Ad-hoc Keys Section ──────────────────────────────────────────────────

interface AdHocKey {
  name: string;
  scope: "user" | "workspace";
  scopeId: string;
  description: string | null;
  last4: string;
  createdAt: number;
  updatedAt: number;
}

const ADHOC_ENDPOINT = agentNativePath("/_agent-native/secrets/adhoc");

function AdHocKeysSection({
  showForm,
  onShowFormChange,
  showEmptyState,
}: {
  showForm: boolean;
  onShowFormChange: (show: boolean) => void;
  showEmptyState: boolean;
}) {
  const t = useT();
  const [keys, setKeys] = useState<AdHocKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [reloadToken, setReloadToken] = useState(0);
  const [formName, setFormName] = useState("");
  const [formValue, setFormValue] = useState("");
  const [formDescription, setFormDescription] = useState("");
  const [formScope, setFormScope] = useState<"user" | "workspace">("user");
  const [formBusy, setFormBusy] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [confirmDeleteName, setConfirmDeleteName] = useState<string | null>(
    null,
  );
  const [deletingName, setDeletingName] = useState<string | null>(null);
  const [toast, setToast] = useState<{
    kind: "ok" | "err";
    text: string;
  } | null>(null);

  const showToast = useCallback(
    (kind: "ok" | "err", text: string, ms = 2500) => {
      setToast({ kind, text });
      setTimeout(() => setToast(null), ms);
    },
    [],
  );

  const reload = useCallback(() => setReloadToken((t) => t + 1), []);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    fetch(ADHOC_ENDPOINT)
      .then(async (r) => {
        if (!r.ok) throw new Error(`Failed to load (${r.status})`);
        return (await r.json()) as AdHocKey[];
      })
      .then((data) => {
        if (!cancelled) {
          setKeys(data);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setKeys([]);
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
  }, [reloadToken]);

  const resetForm = useCallback(() => {
    onShowFormChange(false);
    setFormName("");
    setFormValue("");
    setFormDescription("");
    setFormScope("user");
    setFormError(null);
  }, [onShowFormChange]);

  const handleAdd = useCallback(async () => {
    const name = formName.trim();
    const value = formValue.trim();
    if (!name || !value || formBusy) return;
    setFormBusy(true);
    setFormError(null);
    try {
      const res = await fetch(ADHOC_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          value,
          description: formDescription.trim() || undefined,
          scope: formScope,
        }),
      });
      if (!res.ok) {
        const body = await res
          .json()
          .then((j: { error?: string }) => j.error)
          .catch(() => null);
        setFormError(body ?? `Save failed (${res.status})`);
        return;
      }
      resetForm();
      showToast("ok", "Key saved");
      notifySecretsChanged();
      reload();
    } catch (err: any) {
      setFormError(err?.message ?? "Failed to save");
    } finally {
      setFormBusy(false);
    }
  }, [
    formName,
    formValue,
    formDescription,
    formScope,
    formBusy,
    resetForm,
    showToast,
    reload,
  ]);

  const handleDelete = useCallback(
    async (name: string) => {
      setDeletingName(name);
      try {
        const res = await fetch(
          `${ADHOC_ENDPOINT}/${encodeURIComponent(name)}`,
          {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
          },
        );
        if (!res.ok) {
          showToast("err", "Failed to delete key");
          return;
        }
        showToast("ok", "Key deleted");
        setConfirmDeleteName(null);
        notifySecretsChanged();
        reload();
      } finally {
        setDeletingName(null);
      }
    },
    [showToast, reload],
  );

  return (
    <div className="space-y-2">
      {showForm && (
        <div className="rounded-md border border-border px-2.5 py-2 bg-accent/30 space-y-1.5">
          <TextField
            value={formName}
            onChange={(value) =>
              setFormName(value.toUpperCase().replace(/[^A-Z0-9_-]/g, ""))
            }
            className="w-full text-[11px]"
            aria-label="Key name"
            placeholder="KEY_NAME"
          />
          <TextField
            type="password"
            aria-label="Secret value"
            value={formValue}
            onChange={setFormValue}
            className="w-full text-[11px]"
            placeholder="Secret value"
          />
          <TextField
            value={formDescription}
            aria-label="Description"
            onChange={setFormDescription}
            className="w-full text-[11px]"
            placeholder="Description (optional)"
          />
          <Picker
            mode="select"
            options={[
              { value: "user", label: t("secrets.scopePersonal") },
              { value: "workspace", label: t("secrets.scopeWorkspace") },
            ]}
            value={formScope}
            onChange={(value) => {
              if (value === "user" || value === "workspace") {
                setFormScope(value);
              }
            }}
            aria-label={t("secrets.scopeLabel")}
            description={t(
              formScope === "user"
                ? "secrets.scopePersonalDescription"
                : "secrets.scopeWorkspaceDescription",
            )}
            className="text-[11px]"
          />
          <div className="flex items-center justify-end gap-1.5">
            <Button
              type="button"
              intent="neutral"
              emphasis="outline"
              onClick={resetForm}
              className="rounded border border-border px-2 py-1 text-[10px] font-medium text-muted-foreground hover:text-foreground"
            >
              Cancel
            </Button>
            <Button
              type="button"
              intent="primary"
              emphasis="solid"
              onClick={handleAdd}
              disabled={!formName.trim() || !formValue.trim() || formBusy}
              className="inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium disabled:opacity-40"
              style={{ backgroundColor: "#00B5FF", color: "white" }}
            >
              {formBusy ? (
                <IconLoader2 size={10} className="animate-spin" />
              ) : (
                "Save"
              )}
            </Button>
          </div>
          {formError && <p className="text-[10px] text-red-500">{formError}</p>}
        </div>
      )}

      {loading ? (
        <div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
          <IconLoader2 size={10} className="animate-spin" />
          Loading...
        </div>
      ) : keys.length === 0 && !showForm && showEmptyState ? (
        <p className="text-[10px] text-muted-foreground">No keys added yet.</p>
      ) : keys.length > 0 ? (
        <div className="overflow-hidden rounded-md border border-border">
          {keys.map((key) => (
            <div
              key={`${key.scope}-${key.name}`}
              className="border-b border-border px-2.5 py-2 last:border-b-0"
            >
              <div className="flex items-center justify-between gap-2">
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-1.5">
                    <span className="text-[11px] font-medium text-foreground font-mono truncate">
                      {key.name}
                    </span>
                    <span
                      className={`rounded-full px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${
                        key.scope === "workspace"
                          ? "bg-blue-500/15 text-blue-500"
                          : "bg-accent/60 text-muted-foreground"
                      }`}
                    >
                      {key.scope === "workspace" ? "workspace" : "personal"}
                    </span>
                  </div>
                  {key.description && (
                    <p className="text-[10px] text-muted-foreground mt-0.5">
                      {key.description}
                    </p>
                  )}
                  <div className="flex items-center gap-2 text-[10px] text-muted-foreground mt-0.5">
                    <span>
                      Ending in{" "}
                      <code className="rounded bg-background px-1 py-0.5 text-foreground">
                        {key.last4}
                      </code>
                    </span>
                  </div>
                </div>
                <div className="shrink-0">
                  {confirmDeleteName === key.name ? (
                    <div className="flex items-center gap-1">
                      <Button
                        type="button"
                        intent="danger"
                        emphasis="solid"
                        onClick={() => handleDelete(key.name)}
                        disabled={deletingName === key.name}
                        className="rounded px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide bg-red-500/15 text-red-500 hover:bg-red-500/25 disabled:opacity-40"
                      >
                        {deletingName === key.name ? (
                          <IconLoader2 size={10} className="animate-spin" />
                        ) : (
                          "Confirm"
                        )}
                      </Button>
                      <Button
                        type="button"
                        intent="neutral"
                        emphasis="solid"
                        onClick={() => setConfirmDeleteName(null)}
                        className="rounded px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide bg-accent/60 text-muted-foreground hover:text-foreground"
                      >
                        Cancel
                      </Button>
                    </div>
                  ) : (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          intent="danger"
                          emphasis="ghost"
                          onClick={() => setConfirmDeleteName(key.name)}
                          className="text-muted-foreground hover:text-red-500"
                        >
                          <IconTrash size={12} />
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>Delete</TooltipContent>
                    </Tooltip>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : null}

      {toast && (
        <p
          className={`text-[10px] ${toast.kind === "ok" ? "text-green-500" : "text-red-500"}`}
        >
          {toast.text}
        </p>
      )}
    </div>
  );
}
