import React, { useState } from 'react'; import { Loader2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { apiFetch } from '@/lib/api'; const EMPTY_DRAFT = { first_name: '', last_name: '', email: '', title: '', phone: '' }; /** * "Add a contact" mini-form for the associated-contacts section of a company-scoped detail * panel (Companies / Leads / Deals). Creates the contact via the generic POST /api/contacts * route with `company` locked to `companyName` — unlike the Companies page's own * /api/companies/{id}/contacts route, this doesn't require an existing Company row, so it * works even when the lead/deal's company hasn't synced into one yet. */ export default function AddContactForm({ companyName, onAdded, className }) { const [draft, setDraft] = useState(EMPTY_DRAFT); const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const setField = (key, value) => setDraft((d) => ({ ...d, [key]: value })); const save = async () => { const email = draft.email.trim(); if (!email) { setError('Email is required'); return; } if (!email.includes('@')) { setError('Enter a valid email address'); return; } setSaving(true); setError(''); try { const res = await apiFetch('/api/contacts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ first_name: draft.first_name.trim(), last_name: draft.last_name.trim(), email, title: draft.title.trim(), phone: draft.phone.trim(), company: companyName, }), }); const data = await res.json().catch(() => ({})); if (!res.ok) { setError(typeof data.detail === 'string' ? data.detail : 'Could not save contact'); return; } setDraft(EMPTY_DRAFT); onAdded && onAdded(data); } catch (e) { console.error(e); setError('Network error'); } finally { setSaving(false); } }; return (
Add a contact
setField('first_name', e.target.value)} disabled={saving} /> setField('last_name', e.target.value)} disabled={saving} /> setField('email', e.target.value)} disabled={saving} /> setField('title', e.target.value)} disabled={saving} /> setField('phone', e.target.value)} disabled={saving} />
{error ?

{error}

: null}
); }