import nodemailer from "nodemailer";
import { NextResponse } from "next/server";

export const runtime = "nodejs";

const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024;

const escapeHtml = (value: string) =>
  value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/\"/g, "&quot;")
    .replace(/'/g, "&#39;");

const toText = (value: FormDataEntryValue | null) =>
  typeof value === "string" ? value.trim() : "";

const getSmtpConfig = () => {
  const host = process.env.SMTP_HOST;
  const port = Number(process.env.SMTP_PORT || 587);
  const secure =
    process.env.SMTP_SECURE === "true" ||
    process.env.SMTP_SECURE === "1" ||
    (process.env.SMTP_SECURE !== "false" && process.env.SMTP_SECURE !== "0" && port === 465);
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;

  if (!host || !user || !pass) {
    return null;
  }

  return { host, port, secure, user, pass };
};

export async function POST(request: Request) {
  try {
    const smtpConfig = getSmtpConfig();

    if (!smtpConfig) {
      return NextResponse.json(
        {
          success: false,
          error: "SMTP is not configured. Set SMTP_HOST, SMTP_PORT, SMTP_USER, and SMTP_PASS.",
        },
        { status: 500 }
      );
    }

    const formData = await request.formData();
    const fullname = toText(formData.get("fullname"));
    const email = toText(formData.get("email"));
    const mobile = toText(formData.get("mobile"));
    const role = toText(formData.get("role"));
    const projectType = toText(formData.get("projectType"));
    const productOfInterest = toText(formData.get("productOfInterest"));
    const estimatedArea = toText(formData.get("estimatedArea"));
    const message = toText(formData.get("message"));
    const subject = toText(formData.get("subject")) || `New Contact Form Submission from ${fullname || email || "Website Visitor"}`;

    if (!fullname || !email || !mobile || !role || !projectType || !productOfInterest || !estimatedArea) {
      return NextResponse.json(
        {
          success: false,
          error: "Please complete all required fields before sending.",
        },
        { status: 400 }
      );
    }

    const attachment = formData.get("attachment");
    const attachments = [] as Array<{
      filename: string;
      content: Buffer;
      contentType?: string;
    }>;

    if (attachment instanceof File && attachment.size > 0) {
      if (attachment.size > MAX_ATTACHMENT_SIZE) {
        return NextResponse.json(
          {
            success: false,
            error: "The attached file is too large. Please keep it under 10 MB.",
          },
          { status: 413 }
        );
      }

      const fileBuffer = Buffer.from(await attachment.arrayBuffer());
      attachments.push({
        filename: attachment.name || "attachment",
        content: fileBuffer,
        contentType: attachment.type || undefined,
      });
    }

    const contactTo = process.env.CONTACT_TO_EMAIL || smtpConfig.user;
    const fromAddress = process.env.CONTACT_FROM_EMAIL || smtpConfig.user;
    const transporter = nodemailer.createTransport({
      host: smtpConfig.host,
      port: smtpConfig.port,
      secure: smtpConfig.secure,
      auth: {
        user: smtpConfig.user,
        pass: smtpConfig.pass,
      },
    });

    const plainText = [
      `Full name: ${fullname}`,
      `Email: ${email}`,
      `Mobile: ${mobile}`,
      `Role: ${role}`,
      `Project type: ${projectType}`,
      `Product of interest: ${productOfInterest}`,
      `Estimated area: ${estimatedArea}`,
      `Message: ${message || "N/A"}`,
      `Attachment: ${attachments.length ? attachments[0].filename : "None"}`,
    ].join("\n");

    const html = `
      <div style="font-family: Arial, sans-serif; line-height: 1.6; color: #111827;">
        <h2 style="margin: 0 0 16px;">New Contact Form Submission</h2>
        <table cellpadding="0" cellspacing="0" style="border-collapse: collapse; width: 100%; max-width: 720px;">
          <tr><td style="padding: 8px 0; font-weight: 700; width: 180px;">Full name</td><td>${escapeHtml(fullname)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Email</td><td>${escapeHtml(email)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Mobile</td><td>${escapeHtml(mobile)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Role</td><td>${escapeHtml(role)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Project type</td><td>${escapeHtml(projectType)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Product of interest</td><td>${escapeHtml(productOfInterest)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Estimated area</td><td>${escapeHtml(estimatedArea)}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700; vertical-align: top;">Message</td><td>${escapeHtml(message || "N/A").replace(/\n/g, "<br />")}</td></tr>
          <tr><td style="padding: 8px 0; font-weight: 700;">Attachment</td><td>${attachments.length ? escapeHtml(attachments[0].filename) : "None"}</td></tr>
        </table>
      </div>
    `;

    await transporter.sendMail({
      from: `iRoof Contact Form <${fromAddress}>`,
      to: contactTo,
      replyTo: email,
      subject,
      text: plainText,
      html,
      attachments,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Contact form error:", error);

    return NextResponse.json(
      {
        success: false,
        error: "Unable to send the message right now.",
      },
      { status: 500 }
    );
  }
}
