// components/LeadModal.tsx 'use client'; import React, { useState } from 'react'; import { X, Phone, Building2, Calendar, Flame, Clock, Sparkles, Send, MessageSquare, CheckCircle2, Plus, Trash2, ArrowRight, ExternalLink, Save, Tag, AlertTriangle, History } from 'lucide-react'; import { PIPELINE_STAGES, OBJECTION_PLAYBOOK } from '@/lib/automation'; interface Room { id?: string; name: string; capacity?: number | null; pricePerPerson?: number | null; } interface Activity { id: string; type: string; channel?: string | null; notes?: string | null; performedBy?: string | null; createdAt: string; } interface Lead { id: string; name: string; managerName?: string | null; phone: string; city: string; district?: string | null; instagram?: string | null; website?: string | null; address?: string | null; stage: string; temperature: string; temperatureScore: number; nextFollowupDate?: string | null; nextFollowupChannel?: string | null; nextActionNote?: string | null; loopIndex: number; salesChannels?: string | null; deadSlots?: string | null; biggestPain?: string | null; coreDesire?: string | null; hookForEkipa?: string | null; smsTag?: string | null; objectionStatus?: string | null; potentialDealValue?: number | null; rooms?: Room[]; activities?: Activity[]; } interface LeadModalProps { lead: Lead | null; isOpen: boolean; onClose: () => void; onRefresh: () => void; } export function LeadModal({ lead, isOpen, onClose, onRefresh }: LeadModalProps) { if (!isOpen || !lead) return null; const [activeTab, setActiveTab] = useState<'info' | 'ai' | 'activities'>('info'); const [formData, setFormData] = useState>({ ...lead }); const [saving, setSaving] = useState(false); const [advancing, setAdvancing] = useState(false); // AI extraction state const [callNotesInput, setCallNotesInput] = useState(''); const [aiExtracting, setAiExtracting] = useState(false); const [aiSuccessMessage, setAiSuccessMessage] = useState(''); // New room state const [newRoomName, setNewRoomName] = useState(''); const [newRoomCap, setNewRoomCap] = useState(6); const [newRoomPrice, setNewRoomPrice] = useState(250000); // New activity state const [activityType, setActivityType] = useState('تماس تلفنی'); const [activityNote, setActivityNote] = useState(''); const [activitySubmitting, setActivitySubmitting] = useState(false); const handleSaveLead = async () => { setSaving(true); try { const payload: any = { ...formData, ownerName: (formData as any).ownerName || (formData as any).managerName, ownerPhone: (formData as any).ownerPhone || (formData as any).phone, nextAction: (formData as any).nextAction || (formData as any).nextActionNote, nextChannel: (formData as any).nextChannel || (formData as any).nextFollowupChannel, painPoint: (formData as any).painPoint || (formData as any).biggestPain, aspiration: (formData as any).aspiration || (formData as any).coreDesire, ekipaHook: (formData as any).ekipaHook || (formData as any).hookForEkipa, }; const res = await fetch(`/api/leads/${lead.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); if (res.ok) { onRefresh(); alert('اطلاعات با موفقیت ذخیره شد.'); } } catch (err) { console.error(err); } finally { setSaving(false); } }; const handleAdvanceStage = async () => { setAdvancing(true); try { const res = await fetch(`/api/leads/${lead.id}/advance`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ notes: 'ارتقای مرحله از پروفایل لید' }) }); if (res.ok) { onRefresh(); onClose(); } } catch (err) { console.error(err); } finally { setAdvancing(false); } }; const handleAiExtract = async () => { if (!callNotesInput.trim()) { alert('لطفاً ابتدا یادداشت مکالمه را وارد کنید.'); return; } setAiExtracting(true); setAiSuccessMessage(''); try { const res = await fetch('/api/ai/extract', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ leadId: lead.id, text: callNotesInput }) }); const data = await res.json(); if (data.success && data.extracted) { const ext = data.extracted; setFormData((prev) => ({ ...prev, salesChannels: ext.salesChannels ? ext.salesChannels.join(', ') : prev.salesChannels, deadSlots: ext.deadSlots || prev.deadSlots, biggestPain: ext.biggestPain || prev.biggestPain, coreDesire: ext.coreDesire || prev.coreDesire, hookForEkipa: ext.hookForEkipa || prev.hookForEkipa, objectionStatus: ext.objectionStatus || prev.objectionStatus, smsTag: ext.suggestedSmsTag || prev.smsTag })); setAiSuccessMessage('اطلاعات با هوش مصنوعی استخراج و فرم بروزرسانی شد.'); } } catch (err) { console.error(err); } finally { setAiExtracting(false); } }; const handleAddActivity = async (e: React.FormEvent) => { e.preventDefault(); if (!activityNote.trim()) return; setActivitySubmitting(true); try { const res = await fetch(`/api/leads/${lead.id}/activities`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: activityType, notes: activityNote }) }); if (res.ok) { setActivityNote(''); onRefresh(); } } catch (err) { console.error(err); } finally { setActivitySubmitting(false); } }; const handleAddRoom = () => { if (!newRoomName.trim()) return; const currentRooms = formData.rooms || []; setFormData({ ...formData, rooms: [ ...currentRooms, { name: newRoomName.trim(), capacity: Number(newRoomCap) || 6, pricePerPerson: Number(newRoomPrice) || 250000 } ] }); setNewRoomName(''); }; const handleRemoveRoom = (index: number) => { const currentRooms = formData.rooms || []; setFormData({ ...formData, rooms: currentRooms.filter((_, idx) => idx !== index) }); }; return (
{/* Modal Top Bar */}
{lead.name.substring(0, 2)}

{lead.name}

{lead.temperature} ({lead.temperatureScore} امتیاز)
{lead.city} {lead.district ? `(${lead.district})` : ''} • {lead.stage} • {lead.phone}
{/* Tab Headers */}
{/* Modal Body */}
{/* TAB 1: INFO & ROOMS */} {activeTab === 'info' && (
{/* General Fields */}

اطلاعات تماس و مدیریت

setFormData({ ...formData, managerName: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, phone: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, city: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, district: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, instagram: e.target.value })} placeholder="@escaperoom" className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, website: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
{/* Pipeline Status Fields */}

وضعیت پایپ‌لاین و پیگیری

setFormData({ ...formData, loopIndex: Number(e.target.value) })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
setFormData({ ...formData, nextActionNote: e.target.value })} className="w-full text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500" />
{/* Rooms Section */}

اتاق‌های فرار مجموعه ({formData.rooms?.length || 0} اتاق)

{/* Rooms List */}
{(formData.rooms || []).map((room, idx) => (
{idx + 1} {room.name} ظرفیت: {room.capacity || 6} نفر قیمت هر نفر: {(room.pricePerPerson || 250000).toLocaleString('fa-IR')} تومان
))}
{/* Add Room Row */}
setNewRoomName(e.target.value)} className="text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500 flex-1" /> setNewRoomCap(Number(e.target.value))} className="text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500 w-20" /> setNewRoomPrice(Number(e.target.value))} className="text-xs px-3 py-2 rounded-xl border border-slate-300 focus:ring-2 focus:ring-teal-500 w-32" />
{/* Save Button */}
)} {/* TAB 2: AI INSIGHTS */} {activeTab === 'ai' && (
{/* Call Note Input & AI Button */}
استخراج خودکار اطلاعات لید از متن تماس (AI)

متن خلاصه مکالمه یا یادداشت صوتی تبدیل‌شده به متن را در کادر زیر وارد کنید و دکمه را بزنید؛ سیستم هوشمند فیلدهای سانس‌های خالی، خواست قلبی، چالش‌ها و اعتراض مشتری را خودکار استخراج می‌کند.