'use client'; import { useState, useEffect, FormEvent, ChangeEvent } from 'react'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; interface Customer { id: string; name: string; url: string; email: string; createdAt: string; modifiedAt: string; } interface EditCustomerProps { id?: string; // Optional for new customer } export default function EditCustomer({ id }: EditCustomerProps) { const router = useRouter(); const [formData, setFormData] = useState({ name: '', url: '', email: '', }); const [isLoading, setIsLoading] = useState(!!id); // Only loading if editing const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); // Fetch customer data if editing useEffect(() => { const fetchCustomer = async () => { if (!id) { setIsLoading(false); return; } try { const response = await fetch(`/api/customers/${id}`); if (!response.ok) { throw new Error('Failed to fetch customer'); } const customer: Customer = await response.json(); setFormData({ name: customer.name, url: customer.url || '', email: customer.email, }); setIsLoading(false); } catch (err) { setError('Failed to load customer data'); setIsLoading(false); } }; fetchCustomer(); }, [id]); const handleChange = (e: ChangeEvent) => { const { name, value } = e.target; setFormData((prev) => ({ ...prev, [name]: value })); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setIsSubmitting(true); setError(null); try { // Validate form if (!formData.name || !formData.email) { throw new Error('Name and email are required'); } // Determine if creating or updating const url = id ? `/api/customers/${id}` : '/api/customers'; const method = id ? 'PUT' : 'POST'; // Submit the form const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(formData), }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || `Failed to ${id ? 'update' : 'create'} customer`); } // Redirect to customers list on success router.push('/admin/customers'); router.refresh(); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); setIsSubmitting(false); } }; if (isLoading) { return
Loading...
; } return (

{id ? 'Edit Customer' : 'Add New Customer'}

Back to Customers
{error && (

{error}

)}
Cancel
); }