import React, { useState, FormEvent } from "react"; import { ClientAddress, CreateClientAddressPayload } from "../../types/client"; import { Input, Select, Button } from "../UI"; // ─── Types ──────────────────────────────────────────────────────────────────── interface ClientAddressFormProps { clientId: string; initialValues?: Partial; onSubmit: (data: CreateClientAddressPayload) => Promise; onCancel: () => void; submitLabel?: string; } type FormErrors = Partial>; // ─── Validation ─────────────────────────────────────────────────────────────── function validate(v: CreateClientAddressPayload): FormErrors { const e: FormErrors = {}; if (!v.label.trim()) e.label = "Label is required."; if (!v.street.trim()) e.street = "Street is required."; if (!v.city.trim()) e.city = "City is required."; if (!v.state.trim()) e.state = "State / Province is required."; if (!v.postalCode.trim()) e.postalCode = "Postal code is required."; if (!v.country.trim()) e.country = "Country is required."; return e; } // Common address labels – quick-pick for the user const LABEL_PRESETS = ["Billing", "Shipping", "Head Office", "Branch", "Warehouse", "Other"]; // ─── Component ──────────────────────────────────────────────────────────────── export default function ClientAddressForm({ clientId, initialValues = {}, onSubmit, onCancel, submitLabel = "Save address", }: ClientAddressFormProps) { const [values, setValues] = useState({ clientId, label: initialValues.label ?? "", street: initialValues.street ?? "", city: initialValues.city ?? "", state: initialValues.state ?? "", postalCode: initialValues.postalCode ?? "", country: initialValues.country ?? "", isPrimary: initialValues.isPrimary ?? false, }); const [errors, setErrors] = useState({}); const [submitting, setSubmitting] = useState(false); const set = (field: keyof Omit) => (e: React.ChangeEvent) => { setValues((v) => ({ ...v, [field]: e.target.value })); if (errors[field]) setErrors((er) => ({ ...er, [field]: undefined })); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); const errs = validate(values); if (Object.keys(errs).length) { setErrors(errs); return; } setSubmitting(true); try { await onSubmit(values); } catch { /* parent surfaces the error */ } finally { setSubmitting(false); } }; return (
{/* Label + Primary toggle */}
{/* Street */} {/* City + State */}
{/* Postal code + Country */}
{/* Actions */}
); }