"use client"; import { useMemo, useState } from "react"; import type { FormEvent, ReactNode } from "react"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import type { CustomerContact, CustomerContactPayload } from "@/types/customer"; const emptyContact: CustomerContactPayload = { first_name: "", last_name: "", position: "", email: "", phone: "", mobile: "", is_primary: false, notes: "", }; type Props = { open: boolean; contact?: CustomerContact | null; pending?: boolean; serverError?: string; onOpenChange: (open: boolean) => void; onSubmit: (payload: CustomerContactPayload) => Promise; }; export default function CustomerContactFormDialog({ open, contact, pending = false, serverError, onOpenChange, onSubmit, }: Props) { const initialForm = contact ? { first_name: contact.first_name, last_name: contact.last_name, position: contact.position, email: contact.email, phone: contact.phone, mobile: contact.mobile, is_primary: contact.is_primary, notes: contact.notes, } : emptyContact; return ( {open && ( onOpenChange(false)} onSubmit={onSubmit} /> )} ); } function ContactForm({ initialForm, pending, serverError, onCancel, onSubmit, }: { initialForm: CustomerContactPayload; pending: boolean; serverError?: string; onCancel: () => void; onSubmit: (payload: CustomerContactPayload) => Promise; }) { const [form, setForm] = useState(initialForm); const errors = useMemo(() => ({ name: form.first_name.trim() || form.last_name.trim() ? "" : "Vorname oder Nachname erforderlich", email: !form.email || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email) ? "" : "Gültige E-Mail erforderlich", }), [form.email, form.first_name, form.last_name]); const valid = Object.values(errors).every((error) => !error); function update(key: K, value: CustomerContactPayload[K]) { setForm((current) => ({ ...current, [key]: value })); } async function handleSubmit(event: FormEvent) { event.preventDefault(); if (!valid) { return; } await onSubmit({ ...form, email: form.email?.trim() || null, }); } return (
Ansprechpartner {initialForm.first_name || initialForm.last_name ? "bearbeiten" : "hinzufügen"} Ansprechpartnerdaten und Primärkennzeichnung pflegen.
update("first_name", event.target.value)} /> update("last_name", event.target.value)} /> update("position", event.target.value)} /> update("email", event.target.value)} /> update("phone", event.target.value)} /> update("mobile", event.target.value)} />
update("notes", event.target.value)} /> {serverError &&

{serverError}

}
); } function Field({ label, error, children, }: { label: string; error?: string; children: ReactNode; }) { return (
{children} {error &&

{error}

}
); }