import { NextResponse } from "next/server"
import nodemailer from "nodemailer"

export async function POST(req: Request) {
    try {
        const body = await req.json()
        const { name, email, phone, service, message, recaptchaToken, recaptchaAction } = body
        const recaptchaSecret =
            process.env.RECAPTCHA_SECRET_KEY ||
            "6LfqD1osAAAAAEbpEApPkiQUbyjdKYx2OvhY2XTk"
        const minScore = Number(process.env.RECAPTCHA_MIN_SCORE) || 0.5

        if (!recaptchaToken) {
            return NextResponse.json({ error: "Missing reCaptcha token" }, { status: 400 })
        }

        // 1. Verify reCaptcha v3
        const verifyBody = new URLSearchParams({
            secret: recaptchaSecret,
            response: recaptchaToken,
        })
        const recaptchaResponse = await fetch("https://www.google.com/recaptcha/api/siteverify", {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: verifyBody.toString(),
        })
        const recaptchaData = await recaptchaResponse.json()

        if (!recaptchaData.success || recaptchaData.action !== recaptchaAction || recaptchaData.score < minScore) {
            return NextResponse.json({ error: "reCaptcha verification failed" }, { status: 400 })
        }

        // 2. Configure Nodemailer
        // NOTE: In a real environment, you'd use your SMTP credentials (Gmail, SendGrid, etc.)
        const smtpUser = process.env.SMTP_USER
        const smtpPass = process.env.SMTP_PASS
        if (!smtpUser || !smtpPass) {
            return NextResponse.json({ error: "SMTP is not configured" }, { status: 500 })
        }

        const transporter = nodemailer.createTransport({
            host: process.env.SMTP_HOST || "smtp.gmail.com",
            port: Number(process.env.SMTP_PORT) || 587,
            secure: false,
            auth: {
                user: smtpUser,
                pass: smtpPass,
            },
        })

        // 3. Create HTML Email
        const htmlEmail = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style>
          body { font-family: "Segoe UI", Arial, sans-serif; line-height: 1.6; color: #1a1a1a; margin: 0; padding: 0; }
          .container { max-width: 640px; margin: 24px auto; border: 1px solid #e2e8f0; border-radius: 16px; overflow: hidden; }
          .header { background: #D9A321; color: #111827; padding: 20px 24px; font-weight: 700; }
          .section { padding: 20px 24px; border-top: 1px solid #f1f5f9; background: #ffffff; }
          .title { font-size: 16px; font-weight: 800; margin: 0 0 12px; }
          .label { font-weight: 700; font-size: 12px; text-transform: uppercase; color: #6b7280; margin-top: 12px; }
          .value { font-size: 14px; color: #111827; background: #f8fafc; padding: 10px 12px; border-radius: 10px; border: 1px solid #f1f5f9; }
          .footer { padding: 16px 24px; font-size: 12px; color: #6b7280; background: #f8fafc; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">SkyFly Travel - Uj uzenet / New message</div>

          <div class="section">
            <div class="title">Magyar</div>
            <div class="label">Nev</div>
            <div class="value">${name}</div>
            <div class="label">Email</div>
            <div class="value">${email}</div>
            <div class="label">Telefonszam</div>
            <div class="value">${phone || "-"}</div>
            <div class="label">Szolgaltatas tipusa</div>
            <div class="value">${service}</div>
            <div class="label">Uzenet</div>
            <div class="value" style="white-space: pre-wrap;">${message}</div>
          </div>

          <div class="section">
            <div class="title">English</div>
            <div class="label">Name</div>
            <div class="value">${name}</div>
            <div class="label">Email</div>
            <div class="value">${email}</div>
            <div class="label">Phone</div>
            <div class="value">${phone || "-"}</div>
            <div class="label">Service type</div>
            <div class="value">${service}</div>
            <div class="label">Message</div>
            <div class="value" style="white-space: pre-wrap;">${message}</div>
          </div>

          <div class="footer">&copy; 2026 SkyFly Travel</div>
        </div>
      </body>
      </html>
    `
// 4. Send Email
        await transporter.sendMail({
            from: `"SkyFly Web" <${process.env.MAIL_FROM || smtpUser}>`,
            to: "bognar.szilard83@gmail.com",
            subject: `Weboldal uzenet / Website message: ${name} (${service})`,
            html: htmlEmail,
        })

        return NextResponse.json({ success: true })
    } catch (error) {
        console.error("Email error:", error)
        return NextResponse.json({ error: "Failed to send email" }, { status: 500 })
    }
}
