import nodemailer from 'nodemailer'

interface ContactBody {
  name: string
  countryCode?: string
  phone?: string
  email: string
  subject: string
  message: string
}

const SUBJECT_LABELS: Record<string, string> = {
  programs: 'Learn About Programs',
  partner: 'Partnership',
  volunteer: 'Volunteering',
  other: 'Other',
}

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
}

function renderEmailHtml(name: string, subjectLabel: string, phone: string, message: string): string {
  const safeName = escapeHtml(name)
  const safeSubject = escapeHtml(subjectLabel)
  const safePhone = escapeHtml(phone)
  const safeMessage = escapeHtml(message).replace(/\n/g, '<br>')
  const year = new Date().getFullYear()

  return `
<body style="margin: 0; padding-top: 40px; background-color: #F9F9F9; font-family: Segoe UI, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#F9F9F9">
    <tr>
      <td align="center" valign="top">
        <table width="600" cellpadding="0" cellspacing="0" border="0" style="background-color: #FFFFFF; padding: 0; max-width: 100%;">
          <tr>
            <td style="padding: 50px 53px 0 53px;">
              <table width="100%" cellpadding="0" cellspacing="0" style="width: 100%;">
                <tr>
                  <td align="left" valign="middle">
                    <img src="https://assets.motivit.com/images/dleag/email-template.png" alt="DLEAG Logo" style="display: block; height: 40px;">
                  </td>
                  <td align="right" valign="middle">
                    <a href="https://www.facebook.com/dleag.org" style="text-decoration: none; display: inline-block; margin-left: 8px;">
                      <img src="https://assets.motivit.com/images/dleag/template-fb-logo2.png" alt="Facebook" style="display: inline-block; height: 24px;">
                    </a>
                    <a href="https://www.instagram.com/dleag_org" style="text-decoration: none; display: inline-block; margin-left: 8px;">
                      <img src="https://assets.motivit.com/images/dleag/template-ig-logo2.png" alt="Instagram" style="display: inline-block; height: 24px;">
                    </a>
                    <a href="https://www.linkedin.com/company/dleag-org" style="text-decoration: none; display: inline-block; margin-left: 8px;">
                      <img src="https://assets.motivit.com/images/dleag/template-linked-logo2.png" alt="LinkedIn" style="display: inline-block; height: 24px;">
                    </a>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="padding: 53px; font-family: Segoe UI, sans-serif; font-size: 14px; color: #000000;">
              <p style="margin: 0 0 20px;"><strong>Hi ${safeName},</strong></p>
              <p style="margin: 0 0 20px;">
                Thank you for contacting
                <span style="color: #70459B;"><strong>DLEAG (Developing Leaders through Equity in Athletics for Girls)!</strong></span>
                Your message has been received, and we truly appreciate your interest in supporting equal opportunities for girls in sports.
              </p>
              <p style="margin: 0 0 20px;">Here's a copy of your message for reference:</p>
              <p style="margin: 0 0 10px;"><strong>SUBJECT:</strong> ${safeSubject}</p>
              <p style="margin: 0 0 10px;"><strong>PHONE:</strong> ${safePhone}</p>
              <p style="margin: 0 0 20px;"><strong>MESSAGE:</strong><i> ${safeMessage}</i></p>
              <p style="margin: 0 0 20px;">
                We'll be in touch soon! In the meantime, feel free to explore more about what we do and how you can support girls at <a href="https://www.dleag.org/" style="color: #70459B; text-decoration: none;">https://www.dleag.org/</a>
              </p>
              <p style="margin: 40px 0 5px; line-height: 1.4;">With gratitude,</p>
              <p style="color: #70459B; margin: 0; line-height: 1.4;"><strong>The DLEAG Team</strong></p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
  <table width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td align="center" valign="top">
        <table cellpadding="0" cellspacing="0" border="0" style="font-family: Segoe UI, sans-serif;">
          <tr>
            <td style="font-size: 11px; color: #001D23; text-align: center; line-height: 16px; padding-top: 20px;">
              <strong>&copy; ${year} DLEAG. All rights reserved.</strong>
            </td>
          </tr>
          <tr>
            <td style="font-size: 11px; color: #001D23; text-align: center; line-height: 16px; padding-bottom: 25px;">
              <strong>501(c)(3) Nonprofit Organization | EIN: 99-3346999</strong>
            </td>
          </tr>
          <tr>
            <td style="font-size: 11px; color: #001D23; text-align: center; line-height: 16px; padding-bottom: 20px;">
              This email was sent from
              <a href="https://www.dleag.org/" style="color: #70459B; text-decoration: none;">https://www.dleag.org/</a>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>`
}

export default defineEventHandler(async (event) => {
  const body = await readBody<ContactBody>(event)

  if (!body?.name || !body.email || !body.subject || !body.message) {
    throw createError({ statusCode: 400, statusMessage: 'Missing required fields' })
  }

  const config = useRuntimeConfig()

  const transporter = nodemailer.createTransport({
    host: config.smtpHost,
    port: Number(config.smtpPort),
    secure: String(config.smtpSecure) === 'true',
    auth: { user: config.smtpUser, pass: config.smtpPass },
    tls: String(config.smtpAllowInsecureTls) === 'true' ? { rejectUnauthorized: false } : undefined,
  })

  const subjectLabel = SUBJECT_LABELS[body.subject] ?? body.subject
  const phone = body.phone ? `${body.countryCode ?? ''} ${body.phone}`.trim() : 'N/A'
  const bcc = config.contactBccEmail
    ?.split(',')
    .map((address: string) => address.trim())
    .filter(Boolean)

  await transporter.sendMail({
    from: { address: config.contactFromEmail, name: 'DLEAG Notifications' },
    to: body.email,
    bcc: bcc?.length ? bcc : undefined,
    replyTo: config.contactFromEmail,
    subject: "Thanks for contacting DLEAG – We'll be in touch soon!",
    text: 'To view the message, please use an HTML compatible email viewer!',
    html: renderEmailHtml(body.name, subjectLabel, phone, body.message),
  })

  return { ok: true }
})
