'use client'; import { useEffect, useState } from 'react'; import { useRouter } from 'next/navigation'; import { crmService, CrmLead, formatPhoneDisplay, buildQuotationWhatsAppUrl } from '@/services/api/crmService'; import { openwaService } from '@/services/api/openwaService'; import { Phone, Mail, ArrowRight, Clock, Sparkles, FileText, XCircle, Send, X } from 'lucide-react'; import { toast } from 'sonner'; export default function QualifiedLeadsPage() { const router = useRouter(); const [leads, setLeads] = useState([]); const [loading, setLoading] = useState(true); // Send Quote Modal State const [quoteTarget, setQuoteTarget] = useState(null); const [quoteTitle, setQuoteTitle] = useState(''); const [quoteAmount, setQuoteAmount] = useState(12500); const [quoteTerms, setQuoteTerms] = useState('6 Months iFixKart Warranty + Free Screen Protection'); const [isSendingQuote, setIsSendingQuote] = useState(false); // Mark Lost Modal State const [lostTarget, setLostTarget] = useState(null); const [lossReason, setLossReason] = useState('Spam / Not Genuine Inquiry'); const [isMarkingLost, setIsMarkingLost] = useState(false); useEffect(() => { loadLeads(); }, []); const loadLeads = async () => { try { setLoading(true); const data = await crmService.getLeads('QUALIFIED'); setLeads(data || []); } catch (err) { setLeads([]); } finally { setLoading(false); } }; const handleOpenQuoteModal = (lead: CrmLead) => { setQuoteTarget(lead); setQuoteTitle(lead.title || 'Device Repair & Service Quote'); }; const handleExecuteSendQuote = async () => { if (!quoteTarget) return; try { setIsSendingQuote(true); // Save structured fields and update status to QUOTE_SENT await crmService.updateLeadStatus( quoteTarget.lead_id, 'QUOTE_SENT', `Quotation Sent: ${quoteTitle} (₹${quoteAmount})`, { quote_amount: Number(quoteAmount), quote_title: quoteTitle, quote_terms: quoteTerms, quote_sent_at: new Date().toISOString() } ); // Dispatch WhatsApp quotation message via OpenWA API toast.loading('Dispatching quotation via WhatsApp...', { id: 'wa-send' }); const res = await openwaService.sendQuotationWhatsApp({ customerName: quoteTarget.title || quoteTarget.first_name, customerPhone: quoteTarget.phone || '', quoteTitle, amount: quoteAmount, terms: quoteTerms }); toast.dismiss('wa-send'); if (res.success) { toast.success('Quotation dispatched via WhatsApp!'); setQuoteTarget(null); router.push(`/whatsapp-web?phone=${res.chatId}`); } else { toast.error(`Lead updated, but WhatsApp dispatch failed: ${res.error}`); setQuoteTarget(null); } } catch (err) { toast.error('Failed to send quote'); } finally { setIsSendingQuote(false); } }; const handleDraftQuoteModule = async (lead: CrmLead) => { try { try { await crmService.updateLeadStatus(lead.lead_id, 'QUOTE_DRAFT', 'Drafting quote in B2B Quotations module'); } catch (apiErr) { // Safe fallback for demo leads or network glitches } const query = new URLSearchParams({ lead_id: lead.lead_id, customer_name: lead.title || lead.first_name || '', name: lead.title || lead.first_name || '', phone: lead.phone || '', email: lead.email || '' }).toString(); router.push(`/crm-quotations?${query}`); } catch (err) { toast.error('Failed to navigate to Quotation Module'); } }; const handleExecuteMarkLost = async () => { if (!lostTarget) return; try { setIsMarkingLost(true); await crmService.updateLeadStatus( lostTarget.lead_id, 'LOST', `Lead marked as LOST. Reason: ${lossReason}` ); toast.info(`Lead marked as LOST (${lossReason})`); setLostTarget(null); loadLeads(); } catch (err) { toast.error('Failed to mark lead as lost'); } finally { setIsMarkingLost(false); } }; return (
Stage 3 of 5

3. Qualified Leads

Leads with verified requirements, confirmed details, and ready for quotation delivery

{loading ? (
Loading Qualified Leads...
) : leads.length === 0 ? (

No qualified leads currently in this stage

Leads advance here after staff confirm requirements with the customer.

) : (
{leads.map((lead) => (

{lead.title || lead.first_name || 'Qualified Inquiry'}

QUALIFIED
{lead.phone && (
{formatPhoneDisplay(lead.phone)}
)} {lead.email && (
{lead.email}
)}
Source: {lead.source} {new Date(lead.created_at).toLocaleDateString()}
{/* Multi-Option Quotation & Loss Actions */}
))}
)} {/* Modal: Interactive Send Quotation */} {quoteTarget && (

Create & Send Quotation

{formatPhoneDisplay(quoteTarget.phone || '')}
setQuoteTitle(e.target.value)} className="w-full bg-background border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden" placeholder="e.g. iPhone 14 Display & Battery Repair Quote" />
setQuoteAmount(e.target.value)} className="w-full bg-background border border-border rounded-lg p-2.5 text-foreground font-bold focus:outline-hidden" placeholder="12500" />