import nodemailer from 'nodemailer'

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT) || 587,
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS,
  },
})

interface SendBriefEmailOptions {
  to: string
  name: string
  company: string
  brief: string
}

interface SendLeadNotificationOptions {
  to: string
  name: string
  company: string
  brief: string
  email: string
  services: string[]
  phone?: string
  contactPreference?: string
}

/**
 * Converts a markdown-style brief string into styled HTML.
 * Handles: **bold**, ---, numbered lists, section headings, paragraphs.
 */
function convertBriefToHtml(brief: string): string {
  const lines = brief.split('\n')
  const outputLines: string[] = []

  for (let i = 0; i < lines.length; i++) {
    let line = lines[i]

    // Horizontal rule
    if (line.trim() === '---') {
      outputLines.push('<hr style="border:none;border-top:1px solid #d1e8f5;margin:20px 0">')
      continue
    }

    // Empty line — paragraph break spacer
    if (line.trim() === '') {
      outputLines.push('<div style="height:8px"></div>')
      continue
    }

    // Bold inline
    line = line.replace(/\*\*(.*?)\*\*/g, '<strong style="color:#191c1d;font-weight:600">$1</strong>')

    // Numbered list items: "1. text" or "2. text"
    const numberedMatch = line.match(/^(\d+)\.\s+(.+)$/)
    if (numberedMatch) {
      outputLines.push(
        `<div style="display:flex;gap:10px;margin:6px 0;line-height:1.65;font-size:14px;color:#374151">` +
          `<span style="font-weight:700;color:#006494;min-width:20px">${numberedMatch[1]}.</span>` +
          `<span>${numberedMatch[2]}</span>` +
          `</div>`
      )
      continue
    }

    // Section heading detection: lines that are entirely bold (e.g. **Heading**)
    const headingMatch = line.match(/^<strong[^>]*>(.*?)<\/strong>$/)
    if (headingMatch) {
      outputLines.push(
        `<p style="margin:16px 0 4px;font-size:15px;font-weight:700;color:#006494;letter-spacing:0.01em">${headingMatch[1]}</p>`
      )
      continue
    }

    // Regular paragraph line
    outputLines.push(
      `<p style="margin:0 0 8px;font-size:14px;line-height:1.7;color:#374151">${line}</p>`
    )
  }

  return outputLines.join('\n')
}

export async function sendBriefToClient({ to, name, brief }: SendBriefEmailOptions) {
  const firstName = name.split(' ')[0] || 'there'
  const htmlBrief = convertBriefToHtml(brief)

  await transporter.sendMail({
    from: `"LetsBe." <${process.env.SMTP_FROM || 'hello@letsbe.biz'}>`,
    to,
    subject: 'Your Project Brief from LetsBe.',
    html: `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your Project Brief from LetsBe.</title>
</head>
<body style="margin:0;padding:0;background-color:#f0f4f8;font-family:'Inter',-apple-system,'Segoe UI',Helvetica,Arial,sans-serif">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0f4f8;padding:32px 16px">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px">

          <!-- HEADER -->
          <tr>
            <td style="background:#ffffff;border-bottom:2px solid #e8eef3;border-radius:16px 16px 0 0;padding:28px 32px;text-align:center">
              <img src="${process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.letsbe.biz'}/images/letsbe-logo-short.png" alt="LetsBe." width="52" style="display:block;margin:0 auto" />
            </td>
          </tr>

          <!-- GREETING -->
          <tr>
            <td style="background:#ffffff;padding:36px 40px 28px">
              <p style="margin:0 0 8px;font-size:22px;font-weight:600;color:#191c1d;line-height:1.3">Hi ${firstName},</p>
              <p style="margin:0;font-size:15px;line-height:1.7;color:#6b7280">
                Thank you for configuring your project with us. Here's your personalized brief — a summary of everything we discussed, ready for your review.
              </p>
            </td>
          </tr>

          <!-- BRIEF CARD -->
          <tr>
            <td style="background:#ffffff;padding:0 40px 36px">
              <div style="background:#f0f7fb;border-left:3px solid #006494;border-radius:12px;padding:28px">
                ${htmlBrief}
              </div>
            </td>
          </tr>

          <!-- DIVIDER -->
          <tr>
            <td style="background:#ffffff;padding:0 40px">
              <hr style="border:none;border-top:1px solid #e5e7eb;margin:0">
            </td>
          </tr>

          <!-- CTA -->
          <tr>
            <td style="background:#ffffff;padding:36px 40px;text-align:center">
              <p style="margin:0 0 6px;font-family:Georgia,'Times New Roman',serif;font-size:20px;font-weight:400;color:#191c1d">Ready to discuss your brief?</p>
              <p style="margin:0 0 28px;font-size:14px;color:#6b7280;line-height:1.6">We'll walk through your goals, answer questions, and outline next steps — no pressure.</p>
              <a href="https://scheduling.letsbe.solutions/matt-ciaccio/letsbe"
                 style="display:inline-block;padding:16px 40px;background:linear-gradient(135deg,#006494 0%,#5BA4D9 100%);color:#ffffff;text-decoration:none;border-radius:10px;font-size:15px;font-weight:600;letter-spacing:0.01em;box-shadow:0 4px 14px rgba(0,100,148,0.35)">
                Book a 30-Minute Call
              </a>
              <p style="margin:20px 0 0;font-size:13px;color:#9ca3af;line-height:1.6">
                Or reply to this email — we'll get back to you within 24 hours.
              </p>
            </td>
          </tr>

          <!-- FOOTER -->
          <tr>
            <td style="background:#f8fafb;border-top:1px solid #e5e7eb;border-radius:0 0 16px 16px;padding:24px 40px;text-align:center">
              <p style="margin:0 0 4px;font-size:13px;font-weight:600;color:#374151">LetsBe Solutions LLC</p>
              <p style="margin:0;font-size:12px;color:#9ca3af;line-height:1.6">Custom websites, software, and infrastructure — designed and built around you.</p>
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>
    `.trim(),
  })
}

export async function sendLeadNotification({
  to,
  name,
  company,
  brief,
  email,
  phone,
  contactPreference,
}: SendLeadNotificationOptions) {
  const adminEmail = process.env.ADMIN_EMAIL || 'hello@letsbe.biz'
  const htmlBrief = convertBriefToHtml(brief)

  // Build contact rows with alternating backgrounds
  const contactRows: string[] = []
  const rowData: Array<{ label: string; value: string; isLink?: string }> = [
    { label: 'Name', value: name },
    { label: 'Company', value: company || '—' },
    { label: 'Email', value: email, isLink: `mailto:${email}` },
  ]
  if (phone) {
    rowData.push({ label: 'Phone', value: phone, isLink: `tel:${phone}` })
  }
  if (contactPreference) {
    rowData.push({ label: 'Preferred Contact', value: contactPreference })
  }

  rowData.forEach((row, idx) => {
    const bg = idx % 2 === 0 ? '#f8fafb' : '#ffffff'
    const valueHtml = row.isLink
      ? `<a href="${row.isLink}" style="color:#006494;text-decoration:none;font-weight:500">${row.value}</a>`
      : `<span style="color:#191c1d">${row.value}</span>`
    contactRows.push(`
      <tr style="background-color:${bg}">
        <td style="padding:10px 16px;font-size:13px;font-weight:600;color:#6b7280;white-space:nowrap;width:140px">${row.label}</td>
        <td style="padding:10px 16px;font-size:14px">${valueHtml}</td>
      </tr>
    `)
  })

  await transporter.sendMail({
    from: `"LetsBe. Configurator" <${process.env.SMTP_FROM || 'hello@letsbe.biz'}>`,
    to: adminEmail,
    subject: `New Lead: ${name}${company ? ` — ${company}` : ''}`,
    html: `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>New Configurator Lead</title>
</head>
<body style="margin:0;padding:0;background-color:#f0f4f8;font-family:'Inter',-apple-system,'Segoe UI',Helvetica,Arial,sans-serif">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0f4f8;padding:32px 16px">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px">

          <!-- HEADER -->
          <tr>
            <td style="background:#ffffff;border-bottom:2px solid #e8eef3;border-radius:16px 16px 0 0;padding:24px 32px">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td>
                    <img src="${process.env.NEXT_PUBLIC_SITE_URL || 'https://staging.letsbe.biz'}/images/letsbe-logo-short.png" alt="LetsBe." width="44" style="display:block;max-width:44px;height:auto" />
                  </td>
                  <td align="right" valign="middle">
                    <span style="display:inline-block;background:#006494;color:#ffffff;font-size:11px;font-weight:700;letter-spacing:0.06em;text-transform:uppercase;padding:5px 14px;border-radius:20px">New Lead</span>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- CONTACT INFO CARD -->
          <tr>
            <td style="background:#ffffff;padding:32px 40px 24px">
              <p style="margin:0 0 16px;font-size:11px;font-weight:700;color:#9ca3af;letter-spacing:0.08em;text-transform:uppercase">Contact Details</p>
              <div style="border:1px solid #e5e7eb;border-radius:10px;overflow:hidden">
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
                  ${contactRows.join('')}
                </table>
              </div>
            </td>
          </tr>

          <!-- BRIEF SECTION -->
          <tr>
            <td style="background:#ffffff;padding:8px 40px 36px">
              <p style="margin:0 0 16px;font-size:11px;font-weight:700;color:#9ca3af;letter-spacing:0.08em;text-transform:uppercase">Project Brief</p>
              <div style="background:#f0f7fb;border-left:3px solid #006494;border-radius:12px;padding:28px">
                ${htmlBrief}
              </div>
            </td>
          </tr>

          <!-- DIVIDER -->
          <tr>
            <td style="background:#ffffff;padding:0 40px">
              <hr style="border:none;border-top:1px solid #e5e7eb;margin:0">
            </td>
          </tr>

          <!-- QUICK ACTION -->
          <tr>
            <td style="background:#ffffff;padding:28px 40px;text-align:center">
              <a href="mailto:${email}?subject=Re: Your LetsBe. Project Brief"
                 style="display:inline-block;padding:14px 36px;background:linear-gradient(135deg,#006494 0%,#5BA4D9 100%);color:#ffffff;text-decoration:none;border-radius:10px;font-size:14px;font-weight:600;letter-spacing:0.01em">
                Reply to Lead
              </a>
            </td>
          </tr>

          <!-- FOOTER -->
          <tr>
            <td style="background:#f8fafb;border-top:1px solid #e5e7eb;border-radius:0 0 16px 16px;padding:20px 40px;text-align:center">
              <p style="margin:0;font-size:12px;color:#9ca3af">LetsBe Solutions LLC — Internal Notification</p>
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>
    `.trim(),
  })
}
