import React, { useEffect, useState } from 'react'; import { Loader2, Search, UserPlus, Building2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { cn } from '@/lib/utils'; import { apiFetch } from '@/lib/api'; /** Search CRM contacts and link one to the deal (`PATCH contact_id`). */ export function DealContactSearch({ linkedContactId, onPatchDeal, className }) { const [q, setQ] = useState(''); const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const [linking, setLinking] = useState(false); useEffect(() => { if (!q.trim()) { setResults([]); return; } const t = setTimeout(async () => { setLoading(true); try { const res = await apiFetch( `/api/contacts?search=${encodeURIComponent(q.trim())}&limit=12&sort_by=created_at&sort_dir=desc` ); const data = await res.json().catch(() => ({})); setResults(res.ok ? data.contacts || [] : []); } catch { setResults([]); } finally { setLoading(false); } }, 280); return () => clearTimeout(t); }, [q]); const pick = async (c) => { setLinking(true); try { await onPatchDeal({ contact_id: c.id }); setQ(''); setResults([]); } finally { setLinking(false); } }; const unlink = async () => { setLinking(true); try { await onPatchDeal({ contact_id: null }); } finally { setLinking(false); } }; return (
Link contact from CRM
setQ(e.target.value)} placeholder="Search name, email, company…" className="pl-9 text-sm bg-white" disabled={linking} /> {loading ? ( ) : null}
{results.length > 0 ? ( ) : null} {linkedContactId ? (
) : null}
); } /** Search distinct company names from contacts; sets deal `account_name`. */ export function DealCompanySearch({ onPatchDeal, className }) { const [q, setQ] = useState(''); const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const [applying, setApplying] = useState(false); useEffect(() => { if (!q.trim()) { setResults([]); return; } const t = setTimeout(async () => { setLoading(true); try { const res = await apiFetch(`/api/company-names?q=${encodeURIComponent(q.trim())}&limit=20`); const data = await res.json().catch(() => ({})); setResults(res.ok ? data.names || [] : []); } catch { setResults([]); } finally { setLoading(false); } }, 280); return () => clearTimeout(t); }, [q]); const pick = async (name) => { setApplying(true); try { await onPatchDeal({ account_name: name }); setQ(''); setResults([]); } finally { setApplying(false); } }; return (
Add company from CRM (account name)
setQ(e.target.value)} placeholder="Search company names…" className="pl-9 text-sm bg-white" disabled={applying} /> {loading ? ( ) : null}
{results.length > 0 ? ( ) : null}
); }