"use client"; import { useRouter } from "next/navigation"; import { useState } from "react"; type EstimateAction = "approve" | "decline" | "question"; type EstimateActionsProps = { token: string; }; type ActionResponse = { message?: string; }; const actionLabels: Record = { approve: "Freigeben", decline: "Ablehnen", question: "Rückfrage senden", }; async function readActionMessage(response: Response) { try { const body = await response.json() as ActionResponse; return body.message || "Die Aktion konnte nicht abgeschlossen werden."; } catch { return "Die Aktion konnte nicht abgeschlossen werden."; } } export function EstimateActions({ token }: EstimateActionsProps) { const router = useRouter(); const [activeForm, setActiveForm] = useState | null>(null); const [message, setMessage] = useState(""); const [pendingAction, setPendingAction] = useState(null); const [feedback, setFeedback] = useState<{ type: "success" | "error"; text: string } | null>(null); async function submitAction(action: EstimateAction, actionMessage = "") { setPendingAction(action); setFeedback(null); try { const response = await fetch(`/api/status/${encodeURIComponent(token)}/estimate/${action}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message: actionMessage.trim() || null }), }); const responseMessage = await readActionMessage(response); if (!response.ok) { setFeedback({ type: "error", text: responseMessage }); return; } setMessage(""); setActiveForm(null); setFeedback({ type: "success", text: responseMessage }); router.refresh(); } catch { setFeedback({ type: "error", text: "Die Aktion konnte momentan nicht gesendet werden. Bitte versuchen Sie es erneut.", }); } finally { setPendingAction(null); } } const isPending = pendingAction !== null; return (
{activeForm && (
{ event.preventDefault(); void submitAction(activeForm, message); }} >