"use server"

import { sendEmail, formatFormDataAsHTML } from "@/lib/email"

export async function submitVolunteerApplication(formData: FormData) {
  try {
    const data = {
      "Form Type": "Volunteer Application",
      "Full Name": formData.get("fullName") as string,
      Email: formData.get("email") as string,
      Phone: formData.get("phone") as string,
      City: formData.get("city") as string,
      "Date of Birth": formData.get("dateOfBirth") as string,
      "Areas of Interest": formData.get("interests") as string,
      "Previous Experience": formData.get("experience") as string,
      Availability: formData.get("availability") as string,
      "Why Volunteer": formData.get("motivation") as string,
      "Criminal Record": formData.get("criminalRecord") === "yes" ? "Yes" : "No",
      "Privacy Consent": formData.get("privacyConsent") === "true" ? "Yes" : "No",
      "Submitted At": new Date().toLocaleString("en-ZA", { timeZone: "Africa/Johannesburg" }),
    }

    const emailBody = formatFormDataAsHTML(data)
    await sendEmail({
      subject: `New Volunteer Application - ${data["Full Name"]}`,
      body: emailBody,
      replyTo: data.Email,
    })

    return {
      success: true,
      message: "Thank you for your application! We'll review it and get back to you soon.",
    }
  } catch (error) {
    console.error("Volunteer application error:", error)
    return {
      success: false,
      message: "There was an error submitting your application. Please try again.",
    }
  }
}
