import { type FormEvent, useState } from "react"; import { ApiClientError, apiClient } from "../api"; interface CreateCardModalProps { isOpen: boolean; deckId: string; onClose: () => void; onCardCreated: () => void; } export function CreateCardModal({ isOpen, deckId, onClose, onCardCreated, }: CreateCardModalProps) { const [front, setFront] = useState(""); const [back, setBack] = useState(""); const [error, setError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const resetForm = () => { setFront(""); setBack(""); setError(null); }; const handleClose = () => { resetForm(); onClose(); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setError(null); setIsSubmitting(true); try { const res = await apiClient.rpc.api.decks[":deckId"].cards.$post( { param: { deckId }, json: { front: front.trim(), back: back.trim(), }, }, { headers: apiClient.getAuthHeader(), }, ); if (!res.ok) { const errorBody = await res.json().catch(() => ({})); throw new ApiClientError( (errorBody as { error?: string }).error || `Request failed with status ${res.status}`, res.status, ); } resetForm(); onCardCreated(); onClose(); } catch (err) { if (err instanceof ApiClientError) { setError(err.message); } else { setError("Failed to create card. Please try again."); } } finally { setIsSubmitting(false); } }; if (!isOpen) { return null; } const isFormValid = front.trim() && back.trim(); return (
{ if (e.target === e.currentTarget) { handleClose(); } }} onKeyDown={(e) => { if (e.key === "Escape") { handleClose(); } }} >

Create New Card

{error && (
{error}
)}