"use server"

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

export async function submitIncidentReport(formData: FormData) {
  try {
    const data = {
      "Form Type": "🚨 URGENT - Incident Report",
      "Incident Type": formData.get("incidentType") as string,
      "Incident Date": formData.get("incidentDate") as string,
      Location: formData.get("location") as string,
      "Detailed Description": formData.get("description") as string,
      "Witnesses Present": formData.get("witnesses") === "yes" ? "Yes" : "No",
      "Witness Details": formData.get("witnessDetails") as string,
      "Reporter Name": formData.get("reporterName") as string,
      "Reporter Contact": formData.get("reporterContact") as string,
      "Immediate Action Taken": formData.get("actionTaken") as string,
      "Support Needed": formData.get("supportNeeded") as string,
      "Police Notified": formData.get("policeNotified") === "yes" ? "Yes" : "No",
      "Consent to Follow Up": formData.get("consentFollowUp") === "true" ? "Yes" : "No",
      "Submitted At": new Date().toLocaleString("en-ZA", { timeZone: "Africa/Johannesburg" }),
    }

    const emailBody = formatFormDataAsHTML(data)
    await sendEmail({
      subject: `🚨 URGENT - Incident Report: ${data["Incident Type"]}`,
      body: emailBody,
      replyTo: data["Reporter Contact"],
    })

    return {
      success: true,
      message:
        "Your report has been received. If this is an emergency, please also contact emergency services immediately.",
    }
  } catch (error) {
    console.error("Incident report error:", error)
    return {
      success: false,
      message: "There was an error submitting your report. Please try again or contact us directly.",
    }
  }
}
