Branchwell

Lumen & Gesso / website / app / components / CustomerOrderMessageForm.tsx

1'use client';
2
3import { useState, type FormEvent } from 'react';
4import { useRouter } from 'next/navigation';
5import { ORDER_MESSAGE_LIMIT } from '@/app/lib/order-messages';
6
7export function CustomerOrderMessageForm({ orderId, proofId }: { orderId: string; proofId?: string }) {
8 const router = useRouter();
9 const [note, setNote] = useState('');
10 const [sending, setSending] = useState(false);
11 const [feedback, setFeedback] = useState<{ text: string; error?: boolean } | null>(null);
12
13 const send = async (event: FormEvent<HTMLFormElement>) => {
14 event.preventDefault();
15 if (sending || !note.trim()) return;
16 setSending(true);
17 setFeedback(null);
18 try {
19 const response = await fetch(`/api/orders/${orderId}/message`, {
20 method: 'POST',
21 headers: { 'content-type': 'application/json' },
22 body: JSON.stringify({ note: note.trim(), generationId: proofId, question: !!proofId }),
23 });
24 const result = await response.json().catch(() => null) as { ok?: boolean; emailSent?: boolean; proofReopened?: boolean; error?: string } | null;
25 if (!response.ok || !result?.ok) throw new Error(result?.error ?? 'Could not send your message.');
26 setNote('');
27 const saved = result.proofReopened ? 'Feedback saved. Approval is paused while the studio reviews it.' : proofId ? 'Question sent.' : 'Message saved.';
28 setFeedback({ text: result.emailSent ? saved : `${saved} We couldn’t email the studio a notification.` });
29 router.refresh();
30 } catch (error) {
31 setFeedback({ text: error instanceof Error ? error.message : 'Could not send your message.', error: true });
32 } finally {
33 setSending(false);
34 }
35 };
36
37 return (
38 <form className="approve__form" style={{ marginTop: 14 }} onSubmit={send}>
39 <label className="approve__label" htmlFor="customer-order-note">{proofId ? 'Ask a question about this proof' : 'Message to Lumen & Gesso'}</label>
40 <textarea id="customer-order-note" className="auth__input" rows={3} value={note}
41 onChange={event => setNote(event.target.value)} maxLength={ORDER_MESSAGE_LIMIT} disabled={sending} required />
42 <button type="submit" className="btn btn--secondary btn--md" disabled={sending || !note.trim()}>
43 {sending ? 'Sending…' : proofId ? 'Send question' : 'Send message'}
44 </button>
45 {feedback && <p role={feedback.error ? 'alert' : 'status'} className={feedback.error ? 'auth__error' : undefined}>{feedback.text}</p>}
46 </form>
47 );
48}