import { NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";

export const runtime = "nodejs";


export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, email, phone, company, service, message } = body;

    // Validation
    if (!name || !email || !service || !message) {
      return NextResponse.json(
        { message: "Missing required fields" },
        { status: 400 },
      );
    }

    const emailUser = process.env.EMAIL_HOST_USER || process.env.EMAIL_USER;
    const emailPass = process.env.EMAIL_HOST_PASSWORD || process.env.EMAIL_PASSWORD;
    const emailTo =
      process.env.EMAIL_TO ||
      process.env.CONTACT_RECIPIENT ||
      emailUser;

    if (!emailUser || !emailPass) {
      return NextResponse.json(
        { message: "Email is not configured on the server" },
        { status: 500 },
      );
    }

    // Create a transporter (Gmail SMTP via app password)
    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: emailUser,
        pass: emailPass,
      },
    });

    // Email to you
    const mailOptions = {
      from: `"CCT Website Contact" <${emailUser}>`,
      to: emailTo, // Recipient email
      replyTo: email,
      subject: `New Contact Form Submission from ${name}`,
      html: `
        <!DOCTYPE html>
        <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #00057b; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
            .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 8px 8px; }
            .field { margin-bottom: 15px; }
            .label { font-weight: bold; color: #00057b; }
            .value { margin-top: 5px; }
            .footer { margin-top: 20px; padding-top: 20px; border-top: 2px solid #ffc400; font-size: 12px; color: #666; }
          </style>
        </head>
         <body>
          <div class="container">
            <div class="header">
              <h2 style="margin: 0;">New Contact Form Submission</h2>
              <p style="margin: 5px 0 0 0; opacity: 0.9;">CrownCity Contact Form</p>
            </div>
            <div class="content">
              <div class="field">
                <div class="label">👤 Name:</div>
                <div class="value">${name}</div>
              </div>
              
              <div class="field">
                <div class="label">📧 Email:</div>
                <div class="value"><a href="mailto:${email}">${email}</a></div>
              </div>
              
              ${
                phone
                  ? `
              <div class="field">
                <div class="label">📱 Phone:</div>
                <div class="value">${phone}</div>
              </div>
              `
                  : ""
              }
              
              ${
                company
                  ? `
              <div class="field">
                <div class="label">🏢 Company:</div>
                <div class="value">${company}</div>
              </div>
              `
                  : ""
              }
              
              <div class="field">
                <div class="label">💼 Service Interested In:</div>
                <div class="value">${service}</div>
              </div>
              
              <div class="field">
                <div class="label">💬 Message:</div>
                <div class="value" style="background: white; padding: 15px; border-radius: 5px; white-space: pre-wrap;">${message}</div>
              </div>
              
              <div class="footer">
                <p>⏰ Received: ${new Date().toLocaleString("en-US", {
                  dateStyle: "full",
                  timeStyle: "short",
                })}</p>
                <p>You can reply directly to this email to respond to ${name}</p>
              </div>
            </div>
          </div>
        </body>
        </html>
      `,
    };

    await transporter.sendMail(mailOptions);

    return NextResponse.json(
      { message: "Email sent successfully" },
      { status: 200 },
    );
  } catch (error) {
    console.error("Error sending email:", error);
    return NextResponse.json(
      { message: "Failed to send email" },
      { status: 500 },
    );
  }
}
