'use client'; import { useState, useEffect, FormEvent, ChangeEvent } from 'react'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; interface EmailTemplate { id: string; title: string; content: string; createdAt: string; modifiedAt: string; } interface EditEmailTemplateProps { id?: string; // Optional for new template } export default function EditEmailTemplate({ id }: EditEmailTemplateProps) { const router = useRouter(); const [formData, setFormData] = useState({ title: '', content: '', }); const [isLoading, setIsLoading] = useState(!!id); // Only loading if editing const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); // Fetch email template data if editing useEffect(() => { const fetchEmailTemplate = async () => { if (!id) { setIsLoading(false); return; } try { const response = await fetch(`/api/email-templates/${id}`); if (!response.ok) { throw new Error('Failed to fetch email template'); } const template: EmailTemplate = await response.json(); setFormData({ title: template.title, content: template.content, }); setIsLoading(false); } catch (err) { setError('Failed to load email template data'); setIsLoading(false); } }; fetchEmailTemplate(); }, [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.title || !formData.content) { throw new Error('Title and content are required'); } // Determine if creating or updating const url = id ? `/api/email-templates/${id}` : '/api/email-templates'; 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'} email template`); } // Redirect to email templates list on success router.push('/admin/email-templates'); router.refresh(); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); setIsSubmitting(false); } }; if (isLoading) { return
Loading...
; } return (

{id ? 'Edit Email Template' : 'Add New Email Template'}

Back to Email Templates
{error && (

{error}

)}