"use client" import { useState, useEffect } from "react" import { useForm } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import * as z from "zod" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { Textarea } from "@/components/ui/textarea" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Lead, LeadStatus, User } from "@/types" import { LEAD_SOURCES, LEAD_STATUSES } from "@/lib/constants" import { useNotifications } from "@/providers/notification-provider" const leadFormSchema = z.object({ companyName: z.string().min(1, "Company name is required"), contactName: z.string().min(1, "Contact name is required"), email: z.string().email("Invalid email address"), phone: z.string().optional(), source: z.string().optional(), description: z.string().optional(), status: z.string(), assignedUserId: z.string().optional(), }) type LeadFormValues = z.infer interface LeadFormDialogProps { open: boolean onOpenChange: (open: boolean) => void lead?: Lead | null onSuccess?: () => void } export function LeadFormDialog({ open, onOpenChange, lead, onSuccess }: LeadFormDialogProps) { const isEditing = !!lead const { addNotification } = useNotifications() const [users, setUsers] = useState([]) const [saving, setSaving] = useState(false) useEffect(() => { fetch("/api/users") .then((r) => r.json()) .then((data) => setUsers(data.users || [])) .catch(() => {}) }, []) const form = useForm({ resolver: zodResolver(leadFormSchema), defaultValues: { companyName: "", contactName: "", email: "", phone: "", source: "", description: "", status: "open", assignedUserId: "none", }, }) useEffect(() => { if (lead) { form.reset({ companyName: lead.companyName, contactName: lead.contactName, email: lead.email, phone: lead.phone || "", source: lead.source || "", description: lead.description || "", status: lead.status, assignedUserId: lead.assignedUserId || "none", }) } else { form.reset({ companyName: "", contactName: "", email: "", phone: "", source: "", description: "", status: "open", assignedUserId: "none", }) } }, [lead, form]) async function onSubmit(values: LeadFormValues) { setSaving(true) try { const payload = { ...values, assignedUserId: values.assignedUserId === "none" ? null : values.assignedUserId, } if (isEditing && lead) { const res = await fetch(`/api/leads/${lead.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }) if (!res.ok) throw new Error("Failed to update") addNotification("lead_status_changed", "Lead Updated", `${values.companyName}`, "#") } else { const res = await fetch("/api/leads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }) if (!res.ok) throw new Error("Failed to create") addNotification("lead_created", "New Lead Created", `${values.companyName} — ${values.contactName}`, "#") } onOpenChange(false) onSuccess?.() } catch (e) { console.error("Lead save error:", e) } finally { setSaving(false) } } return ( {isEditing ? "Edit Lead" : "Create New Lead"} {isEditing ? "Update the lead information below." : "Fill in the details to add a new lead."}
( Company Name )} /> ( Contact Name )} /> ( Email )} /> ( Phone )} /> ( Source )} /> ( Status )} />
( Description