"use client"; import { useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ChevronDown, Key, Loader2, Trash2 } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { useAuth } from "@/hooks/use-auth"; import { formatDate, formatDateTime } from "@/lib/format"; import { useTranslations } from "@/lib/i18n/context"; interface ApiTokenInfo { id: string; name: string; permissions: string[]; lastUsedAt: string | null; expiresAt: string | null; createdAt: string; revoked: boolean; } export function ApiSection() { const { t } = useTranslations(); return (

{t("settings.sections.api.title")}

{t("settings.sections.api.description")}

); } function ApiEndpointsCard() { const { t } = useTranslations(); return (

{t("settings.apiEndpointsTitle")}

{t("settings.apiEndpointsDescription")}

{t("settings.apiEndpointMethod")} {t("settings.apiEndpointPath")} {t("settings.apiEndpointAuth")} {t("settings.apiEndpointExample")}
POST /api/ingest/medication Authorization: Bearer hlk_... {`{ "medicationName": "...", "scheduledFor": "..." }`}
); } function ApiTokensCard() { const { t } = useTranslations(); const { isAuthenticated } = useAuth(); const queryClient = useQueryClient(); const [newName, setNewName] = useState(""); const [newToken, setNewToken] = useState(null); const [creating, setCreating] = useState(false); const [tokenMsg, setTokenMsg] = useState(null); const [showRevokedTokens, setShowRevokedTokens] = useState(false); const { data: tokens } = useQuery({ queryKey: ["tokens"], queryFn: async () => { const res = await fetch("/api/tokens"); if (!res.ok) throw new Error("Failed"); return (await res.json()).data as ApiTokenInfo[]; }, enabled: isAuthenticated, }); async function handleCreate(e: React.FormEvent) { e.preventDefault(); setCreating(true); setTokenMsg(null); setNewToken(null); try { const res = await fetch("/api/tokens", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: newName.trim() }), }); const json = await res.json(); if (res.ok) { setNewToken(json.data.token); setNewName(""); queryClient.invalidateQueries({ queryKey: ["tokens"] }); } else { setTokenMsg(json.error || t("common.error")); } } catch { setTokenMsg(t("common.networkError")); } finally { setCreating(false); } } async function handleRevoke(tokenId: string) { const res = await fetch(`/api/tokens/${tokenId}`, { method: "DELETE" }); if (res.ok) { queryClient.invalidateQueries({ queryKey: ["tokens"] }); } } const activeTokens = (tokens ?? []).filter((tok) => !tok.revoked); const revokedTokens = (tokens ?? []).filter((tok) => tok.revoked); const latestActiveUse = activeTokens.reduce((latest, tok) => { if (!tok.lastUsedAt) return latest; if (!latest || new Date(tok.lastUsedAt) > new Date(latest)) { return tok.lastUsedAt; } return latest; }, null); return (

{t("settings.apiTokens")}

{activeTokens.length > 0 && ( {t("settings.configured")} )} {latestActiveUse && ( {t("settings.tokenTableLastUsed")}:{" "} {formatDateTime(latestActiveUse)} )}

{t("settings.apiTokensDescription")}

setNewName(e.target.value)} placeholder={t("settings.tokenNamePlaceholder")} maxLength={100} className="flex-1" />
{newToken && (

{t("settings.tokenCreated")}

{newToken}
)} {tokenMsg && (

{tokenMsg}

)}

{t("settings.activeTokensTitle")}

{activeTokens.length === 0 && ( )} {activeTokens.map((tok, index) => { const isExpired = tok.expiresAt && new Date(tok.expiresAt) < new Date(); return ( ); })}
{t("settings.tokenTableName")} {t("settings.tokenTablePermissions")} {t("settings.tokenTableStatus")} {t("settings.tokenTableCreated")} {t("settings.tokenTableLastUsed")} {t("settings.tokenTableActions")}
{t("settings.noActiveTokens")}
{tok.name} {tok.permissions.join(", ")} {isExpired ? ( {t("settings.tokenExpired")} ) : ( {t("settings.tokenActive")} )} {formatDate(tok.createdAt)} {tok.lastUsedAt ? formatDateTime(tok.lastUsedAt) : t("settings.tokenNeverUsed")} {t("settings.tokenRevoke")} {t("settings.tokenRevokeDescription")} {t("common.cancel")} handleRevoke(tok.id)} > {t("settings.tokenRevoked")}
{revokedTokens.length > 0 && (
{showRevokedTokens && (
{revokedTokens.map((tok, index) => ( ))}
{t("settings.tokenTableName")} {t("settings.tokenTablePermissions")} {t("settings.tokenTableCreated")} {t("settings.tokenTableLastUsed")}
{tok.name} {tok.permissions.join(", ")} {formatDate(tok.createdAt)} {tok.lastUsedAt ? formatDateTime(tok.lastUsedAt) : t("settings.tokenNeverUsed")}
)}
)}
); }