"use client"; import { useState } from "react"; import { X, Send, Paperclip, Loader2, Check } from "lucide-react"; import { Button } from "@/components/ui/button"; import { sendInvoiceEmail } from "@/lib/supabase/invoicing-actions"; export interface InvoiceToSend { id: string; invoice_number: string; client_name: string; client_email: string; total: string; } interface SendInvoiceModalProps { invoices: InvoiceToSend[]; orgName: string; onClose: () => void; onSuccess: () => void; } export default function SendInvoiceModal({ invoices, orgName, onClose, onSuccess }: SendInvoiceModalProps) { const [subject, setSubject] = useState( invoices.length === 1 ? `Invoice ${invoices[0].invoice_number} from ${orgName}` : `Invoices from ${orgName}` ); const [message, setMessage] = useState( invoices.length === 1 ? `Hi ${invoices[0].client_name || "there"},\n\nPlease find attached invoice ${invoices[0].invoice_number} for ${invoices[0].total}.\n\nIf you have any questions, feel free to reach out.\n\nBest regards,\n${orgName}` : `Hi,\n\nPlease find attached invoices from ${orgName}.\n\nIf you have any questions, feel free to reach out.\n\nBest regards,\n${orgName}` ); const [sending, setSending] = useState(false); const [error, setError] = useState(null); const [sentCount, setSentCount] = useState(0); const handleSend = async () => { setError(null); setSending(true); setSentCount(0); for (let i = 0; i < invoices.length; i++) { const inv = invoices[i]; if (!inv.client_email) continue; try { const result = await sendInvoiceEmail({ invoice_number: inv.invoice_number, client_name: inv.client_name, client_email: inv.client_email, total: inv.total, subject, message, org_name: orgName, invoice_id: inv.id, }); if (result.success) { setSentCount((c) => c + 1); } else { setError(result.error || `Failed to send invoice ${inv.invoice_number}`); } } catch (e: any) { setError(e.message || `Failed to send invoice ${inv.invoice_number}`); } } setSending(false); if (sentCount + (sentCount === 0 ? 0 : 0) === invoices.filter((i) => i.client_email).length) { onSuccess(); } }; const validInvoices = invoices.filter((i) => i.client_email); const invalidInvoices = invoices.filter((i) => !i.client_email); return (
e.stopPropagation()}> {/* Header */}

{sentCount > 0 ? `Sent ${sentCount} of ${validInvoices.length}` : `Send ${invoices.length} invoice${invoices.length > 1 ? "s" : ""}`}

{validInvoices.length} with email{invalidInvoices.length > 0 ? `, ${invalidInvoices.length} missing email` : ""}

{/* Invoice list */}
{invoices.map((inv) => (
{inv.invoice_number || "Draft"}
{inv.client_name || "No client"} {inv.total}
))}
{/* Form */}
{error && (
{error}
)}
setSubject(e.target.value)} className="mt-1 w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#1D9E75]/20 focus:border-[#1D9E75]" />