import React, { useState, useEffect } from "react"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "./ui/dialog"; import { Button } from "./ui/button"; import { Textarea } from "./ui/textarea"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; import { Badge } from "./ui/badge"; import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"; import { Separator } from "./ui/separator"; import { AlertCircle, Mail, Send, Eye, MessageSquare, Building2, User, Calendar, } from "lucide-react"; import { supabase, type Debt } from "../lib/supabase"; import { toast } from "sonner"; interface ConversationMessage { id: string; debt_id: string; message_type: string; direction: "inbound" | "outbound"; subject?: string; body: string; from_email?: string; to_email?: string; ai_analysis?: any; created_at: string; } interface ManualResponseDialogProps { debt: Debt; onResponseSent?: () => void; } export function ManualResponseDialog({ debt, onResponseSent, }: ManualResponseDialogProps) { const [open, setOpen] = useState(false); const [subject, setSubject] = useState(""); const [body, setBody] = useState(""); const [isSending, setIsSending] = useState(false); const [lastMessage, setLastMessage] = useState( null ); // Fetch the last inbound message when dialog opens useEffect(() => { if (open) { fetchLastInboundMessage(); generateDefaultResponse(); } }, [open, debt.id]); const fetchLastInboundMessage = async () => { try { const { data, error } = await supabase .from("conversation_messages") .select("*") .eq("debt_id", debt.id) .eq("direction", "inbound") .order("created_at", { ascending: false }) .limit(1) .single(); if (error) { console.error("Error fetching last message:", error); return; } setLastMessage(data); } catch (error) { console.error("Error fetching last message:", error); } }; const generateDefaultResponse = () => { // Generate a default subject line const defaultSubject = `Re: ${ debt.metadata?.subject || `Account ${debt.vendor}` }`; setSubject(defaultSubject); // Generate a basic template response const defaultBody = `Dear ${debt.vendor}, Thank you for your recent correspondence regarding this account. I am writing to discuss the terms of this debt and explore options for resolution. I would like to work with you to find a mutually acceptable solution. Please let me know what options are available for resolving this matter. Thank you for your time and consideration. Sincerely, {{ Your Name }}`; setBody(defaultBody); }; const handleSendResponse = async () => { if (!subject.trim() || !body.trim()) { toast.error("Please fill in both subject and message"); return; } setIsSending(true); try { // Create conversation message const { error: messageError } = await supabase .from("conversation_messages") .insert({ debt_id: debt.id, message_type: "manual_response", direction: "outbound", subject: subject.trim(), body: body.trim(), from_email: debt.metadata?.toEmail || "user@example.com", to_email: debt.metadata?.fromEmail || debt.vendor, message_id: `manual-${Date.now()}`, }); if (messageError) { throw messageError; } // Update debt status const { error: debtError } = await supabase .from("debts") .update({ status: "awaiting_response", last_message_at: new Date().toISOString(), conversation_count: (debt.conversation_count || 0) + 1, }) .eq("id", debt.id); if (debtError) { throw debtError; } // Log the action await supabase.from("audit_logs").insert({ debt_id: debt.id, action: "manual_response_sent", details: { subject: subject.trim(), bodyLength: body.trim().length, sentAt: new Date().toISOString(), }, }); toast.success("Response Sent", { description: "Your manual response has been recorded and the debt status updated.", }); setOpen(false); onResponseSent?.(); } catch (error) { console.error("Error sending manual response:", error); toast.error("Failed to send response", { description: "Please try again or contact support.", }); } finally { setIsSending(false); } }; const formatDate = (dateString: string) => { return new Date(dateString).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); }; return ( Manual Response Required The AI couldn't determine the creditor's intent clearly. Please review their response and compose a manual reply.
{/* Left Column: Creditor's Last Response */}

Creditor's Last Response

{lastMessage ? (
{lastMessage.subject || "No Subject"} {formatDate(lastMessage.created_at)}
{lastMessage.from_email} → You

{lastMessage.body}

{lastMessage.ai_analysis && (
AI Analysis
Intent:{" "} {lastMessage.ai_analysis.intent || "unclear"} {lastMessage.ai_analysis.confidence && ( ( {Math.round( lastMessage.ai_analysis.confidence * 100 )} % confidence) )}
{lastMessage.ai_analysis.reasoning && (
{lastMessage.ai_analysis.reasoning}
)}
)}
) : (

No recent creditor response found

)}
{/* Right Column: Compose Response */}

Compose Your Response

setSubject(e.target.value)} placeholder="Enter subject line..." className="mt-1" />