ifixkart-admin/app/(admin)/crm-leads/qualified/page.tsx

378 lines
15 KiB
TypeScript

'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<CrmLead[]>([]);
const [loading, setLoading] = useState(true);
// Send Quote Modal State
const [quoteTarget, setQuoteTarget] = useState<CrmLead | null>(null);
const [quoteTitle, setQuoteTitle] = useState('');
const [quoteAmount, setQuoteAmount] = useState<number | string>(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<CrmLead | null>(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 (
<div className="p-6 space-y-6 max-w-7xl mx-auto">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-border pb-4">
<div>
<div className="flex items-center gap-2">
<span className="px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-500/10 text-emerald-600 border border-emerald-500/20">
Stage 3 of 5
</span>
<h1 className="text-2xl font-bold text-foreground">3. Qualified Leads</h1>
</div>
<p className="text-xs text-muted-foreground mt-1">
Leads with verified requirements, confirmed details, and ready for quotation delivery
</p>
</div>
</div>
{loading ? (
<div className="py-20 text-center text-muted-foreground animate-pulse text-sm">
Loading Qualified Leads...
</div>
) : leads.length === 0 ? (
<div className="py-16 text-center bg-card border border-border rounded-xl">
<Sparkles className="w-10 h-10 text-emerald-500 mx-auto mb-2 opacity-50" />
<h3 className="text-sm font-semibold text-foreground">No qualified leads currently in this stage</h3>
<p className="text-xs text-muted-foreground mt-1">
Leads advance here after staff confirm requirements with the customer.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{leads.map((lead) => (
<div key={lead.lead_id} className="bg-card border border-border hover:border-emerald-500/50 rounded-xl p-4 shadow-xs space-y-3 flex flex-col justify-between transition-all">
<div className="space-y-2">
<div className="flex items-start justify-between gap-2">
<h3 className="font-semibold text-sm text-foreground">
{lead.title || lead.first_name || 'Qualified Inquiry'}
</h3>
<span className="px-2 py-0.5 rounded-md text-[10px] font-bold bg-emerald-500/10 text-emerald-600">
QUALIFIED
</span>
</div>
<div className="space-y-1 text-xs">
{lead.phone && (
<div className="flex items-center gap-1.5 text-foreground font-medium">
<Phone className="w-3.5 h-3.5 text-muted-foreground" />
{formatPhoneDisplay(lead.phone)}
</div>
)}
{lead.email && (
<div className="flex items-center gap-1.5 text-muted-foreground truncate">
<Mail className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">{lead.email}</span>
</div>
)}
</div>
<div className="flex items-center justify-between text-[10px] text-muted-foreground pt-1">
<span className="bg-muted px-2 py-0.5 rounded-md font-semibold">
Source: {lead.source}
</span>
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{new Date(lead.created_at).toLocaleDateString()}
</span>
</div>
</div>
{/* Multi-Option Quotation & Loss Actions */}
<div className="pt-3 border-t border-border space-y-2">
<div className="flex items-center gap-2">
<button
onClick={() => handleOpenQuoteModal(lead)}
className="flex-1 inline-flex items-center justify-center gap-1 text-xs font-semibold bg-emerald-600 text-white hover:bg-emerald-700 py-1.5 px-3 rounded-lg shadow-xs transition-colors"
>
<Send className="w-3.5 h-3.5" />
<span>Send Quote</span>
</button>
<button
onClick={() => handleDraftQuoteModule(lead)}
className="inline-flex items-center justify-center gap-1 text-xs font-semibold bg-muted text-foreground hover:bg-muted/80 py-1.5 px-2.5 rounded-lg border border-border transition-colors"
title="Draft in B2B Quotation Builder Module"
>
<FileText className="w-3.5 h-3.5 text-primary" />
<span>Draft</span>
</button>
<button
onClick={() => setLostTarget(lead)}
className="inline-flex items-center justify-center p-1.5 rounded-lg border border-rose-200 text-rose-600 hover:bg-rose-50 transition-colors"
title="Mark Lead as Lost"
>
<XCircle className="w-4 h-4" />
</button>
</div>
</div>
</div>
))}
</div>
)}
{/* Modal: Interactive Send Quotation */}
{quoteTarget && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-border pb-3">
<h3 className="text-lg font-bold text-foreground flex items-center gap-2">
<Send className="w-5 h-5 text-emerald-600" />
Create & Send Quotation
</h3>
<button onClick={() => setQuoteTarget(null)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3 text-xs">
<div>
<label className="block font-medium mb-1 text-muted-foreground">Customer Mobile (Read-Only)</label>
<div className="p-2.5 bg-muted border border-border rounded-lg font-mono font-bold text-foreground">
{formatPhoneDisplay(quoteTarget.phone || '')}
</div>
</div>
<div>
<label className="block font-medium mb-1">Quotation Title / Service Item</label>
<input
type="text"
required
value={quoteTitle}
onChange={(e) => 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"
/>
</div>
<div>
<label className="block font-medium mb-1">Quote Amount (₹)</label>
<input
type="number"
required
value={quoteAmount}
onChange={(e) => 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"
/>
</div>
<div>
<label className="block font-medium mb-1">Warranty & Terms</label>
<textarea
rows={3}
value={quoteTerms}
onChange={(e) => setQuoteTerms(e.target.value)}
className="w-full bg-background border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden"
placeholder="6 Months Warranty + Free Tempered Glass"
/>
</div>
<div className="p-3 bg-emerald-500/10 border border-emerald-500/20 rounded-lg text-emerald-700 dark:text-emerald-300 text-[11px]">
🚀 Submitting will save structured quote fields, open WhatsApp Web with pre-formatted quote text, and advance lead status to <strong>QUOTE_SENT</strong>.
</div>
<div className="pt-2 flex justify-end gap-2">
<button
type="button"
onClick={() => setQuoteTarget(null)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="button"
disabled={isSendingQuote}
onClick={handleExecuteSendQuote}
className="px-4 py-2 rounded-lg bg-emerald-600 text-white font-semibold hover:bg-emerald-700 flex items-center gap-1.5"
>
{isSendingQuote ? 'Sending...' : 'Send Quote & Launch WhatsApp'}
</button>
</div>
</div>
</div>
</div>
)}
{/* Modal: Mark Lead as Lost */}
{lostTarget && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-border pb-3">
<h3 className="text-lg font-bold text-rose-600 flex items-center gap-2">
<XCircle className="w-5 h-5 text-rose-600" />
Mark Lead as Lost
</h3>
<button onClick={() => setLostTarget(null)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3 text-xs">
<p className="text-muted-foreground">
Select reason for closing lead <strong>{lostTarget.title || lostTarget.phone}</strong>:
</p>
<div>
<label className="block font-medium mb-1">Reason for Loss</label>
<select
value={lossReason}
onChange={(e) => setLossReason(e.target.value)}
className="w-full bg-background border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden"
>
<option value="Spam / Not Genuine Inquiry">Spam / Not Genuine Inquiry</option>
<option value="Budget Mismatch">Budget Mismatch</option>
<option value="Competitor Chosen">Competitor Chosen</option>
<option value="Customer Unresponsive">Customer Unresponsive</option>
</select>
</div>
<div className="pt-2 flex justify-end gap-2">
<button
type="button"
onClick={() => setLostTarget(null)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="button"
disabled={isMarkingLost}
onClick={handleExecuteMarkLost}
className="px-4 py-2 rounded-lg bg-rose-600 text-white font-semibold hover:bg-rose-700"
>
{isMarkingLost ? 'Saving...' : 'Confirm Mark Lost'}
</button>
</div>
</div>
</div>
</div>
)}
</div>
);
}