import { NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { firstName, lastName, email, phone, serviceType, message } = body;

    if (!firstName || typeof firstName !== "string" || firstName.trim().length === 0) {
      return NextResponse.json({ error: "First name is required." }, { status: 400 });
    }
    if (!lastName || typeof lastName !== "string" || lastName.trim().length === 0) {
      return NextResponse.json({ error: "Last name is required." }, { status: 400 });
    }
    if (!email || typeof email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ error: "A valid email address is required." }, { status: 400 });
    }
    if (!phone || typeof phone !== "string" || phone.trim().length === 0) {
      return NextResponse.json({ error: "Phone number is required." }, { status: 400 });
    }
    if (!serviceType || typeof serviceType !== "string" || serviceType.trim().length === 0) {
      return NextResponse.json({ error: "Please select a service type." }, { status: 400 });
    }
    if (!message || typeof message !== "string" || message.trim().length === 0) {
      return NextResponse.json({ error: "Message is required." }, { status: 400 });
    }

    const smtpHost = process.env.SES_SMTP_HOST || "email-smtp.us-east-2.amazonaws.com";
    const smtpPort = parseInt(process.env.SES_SMTP_PORT || "587", 10);
    const smtpUser = process.env.SES_SMTP_USER;
    const smtpPass = process.env.SES_SMTP_PASS;
    const fromEmail = process.env.SES_FROM_EMAIL || "website@buddelectric.net";
    const toEmail = process.env.SES_TO_EMAIL || "buddelectric@grandecom.net";

    if (!smtpUser || !smtpPass) {
      return NextResponse.json({ error: "Email service is not configured." }, { status: 500 });
    }

    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      secure: false,
      auth: {
        user: smtpUser,
        pass: smtpPass,
      },
    });

    const serviceTypeLabels: Record<string, string> = {
      residential: "Residential Service",
      commercial: "Commercial Project",
      generator: "Generator Quote",
      other: "Other",
    };

    const htmlBody = `
      <h2 style="color:#1e293b;">New Contact Form Submission</h2>
      <table style="border-collapse:collapse;width:100%;max-width:600px;">
        <tr><td style="padding:8px;border-bottom:1px solid #e2e8f0;font-weight:bold;">Name</td><td style="padding:8px;border-bottom:1px solid #e2e8f0;">${firstName} ${lastName}</td></tr>
        <tr><td style="padding:8px;border-bottom:1px solid #e2e8f0;font-weight:bold;">Email</td><td style="padding:8px;border-bottom:1px solid #e2e8f0;">${email}</td></tr>
        <tr><td style="padding:8px;border-bottom:1px solid #e2e8f0;font-weight:bold;">Phone</td><td style="padding:8px;border-bottom:1px solid #e2e8f0;">${phone}</td></tr>
        <tr><td style="padding:8px;border-bottom:1px solid #e2e8f0;font-weight:bold;">Service Type</td><td style="padding:8px;border-bottom:1px solid #e2e8f0;">${serviceTypeLabels[serviceType] || serviceType}</td></tr>
        <tr><td style="padding:8px;font-weight:bold;">Message</td><td style="padding:8px;">${message}</td></tr>
      </table>
    `;

    await transporter.sendMail({
      from: fromEmail,
      to: toEmail,
      replyTo: email,
      subject: `New Contact Form Submission from ${firstName} ${lastName}`,
      html: htmlBody,
    });

    return NextResponse.json({ success: true }, { status: 200 });
  } catch {
    return NextResponse.json({ error: "Failed to send your message. Please try again or call us directly." }, { status: 500 });
  }
}
