// thoughts-frontend/components/api-key-list.tsx "use client"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { toast } from "sonner"; import { useAuth } from "@/hooks/use-auth"; import { ApiKey, CreateApiKeySchema, createApiKey, deleteApiKey, } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Copy, KeyRound, Plus, Trash2 } from "lucide-react"; import { format } from "date-fns"; interface ApiKeyListProps { initialApiKeys: ApiKey[]; } export function ApiKeyList({ initialApiKeys }: ApiKeyListProps) { const [keys, setKeys] = useState(initialApiKeys); const [newKey, setNewKey] = useState(null); const { token } = useAuth(); const form = useForm>({ resolver: zodResolver(CreateApiKeySchema), defaultValues: { name: "" }, }); async function onSubmit(values: z.infer) { if (!token) return; try { const newKeyResponse = await createApiKey(values, token); setKeys((prev) => [...prev, newKeyResponse]); setNewKey(newKeyResponse.plaintextKey ?? null); form.reset(); toast.success("API Key created successfully."); } catch { toast.error("Failed to create API key."); } } const handleDelete = async (keyId: string) => { if (!token) return; try { await deleteApiKey(keyId, token); setKeys((prev) => prev.filter((key) => key.id !== keyId)); toast.success("API Key deleted successfully."); } catch { toast.error("Failed to delete API key."); } }; const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text); toast.success("Key copied to clipboard!"); }; return (
Existing Keys These are the API keys associated with your account. {keys.length > 0 ? (
    {keys.map((key) => (
  • {key.name}

    {`Created on ${format(key.createdAt, "PPP")}`}

    {`${key.keyPrefix}...`}

    Are you sure? This will permanently delete the key "{key.name} ". This action cannot be undone. Cancel handleDelete(key.id)}> Delete
  • ))}
) : (

You have no API keys.

)}
{/* Display New Key */} {newKey && ( New API Key Generated Please copy this key and store it securely. You will not be able to see it again. )} Create New API Key Give your new key a descriptive name.
( Key Name )} />
); }