import type { CollectionAfterChangeHook } from 'payload'
import { notifyAddress } from './mail'

/** One row of the little table in the message; empty values are left out rather than shown blank. */
function row(label: string, value?: string | null): string {
  const v = (value || '').trim()
  if (!v) return ''
  return `<tr>
    <td style="padding:6px 0; color:#5B6B82; font-size:14px; white-space:nowrap;">${escape(label)}</td>
    <td style="padding:6px 0 6px 16px; color:#0F1D33; font-size:15px; font-weight:600;">${escape(v)}</td>
  </tr>`
}

function escape(value: string): string {
  return value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c] as string)
}

/**
 * Tell the academy that someone asked to be contacted. The request is already saved by the time this
 * runs, so a mail that fails must never undo it: everything here is inside a try/catch, and a failure is
 * logged for whoever reads the server output.
 */
export const notifyOnNewLead: CollectionAfterChangeHook = async ({ doc, operation, req }) => {
  if (operation !== 'create') return doc
  const { payload } = req
  try {
    const to = await notifyAddress(payload)
    if (!to) return doc

    const site = (process.env.SITE_URL || '').replace(/\/$/, '')
    const link = `${site}/admin/collections/leads/${doc.id}`
    const title = 'وصلك طلب جديد'
    const body = `<!doctype html>
<html lang="ar" dir="rtl"><body style="margin:0; padding:0; background:#F4F7FB;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#F4F7FB; padding:24px 12px;">
  <tr><td align="center">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0"
           style="max-width:560px; background:#ffffff; border-radius:16px; overflow:hidden;
                  font-family:'IBM Plex Sans Arabic',Tahoma,Arial,sans-serif;">
      <tr><td style="background:#113972; padding:20px 24px; color:#ffffff; font-size:18px; font-weight:700;">
        أكاديمية Thinkera
      </td></tr>
      <tr><td style="padding:24px;">
        <p style="margin:0 0 4px; font-size:20px; font-weight:700; color:#0F1D33;">${title}</p>
        <p style="margin:0 0 20px; color:#5B6B82; font-size:15px;">حد سجّل اهتمامه من الموقع. دي بياناته:</p>
        <table role="presentation" cellpadding="0" cellspacing="0" style="width:100%; border-collapse:collapse;">
          ${row('الاسم', doc.name)}
          ${row('البريد', doc.email)}
          ${row('الموبايل', doc.phone)}
          ${row('الصفة', doc.role)}
          ${row('لغة الصفحة', doc.locale === 'en' ? 'English' : 'العربية')}
          ${row('السؤال', doc.note)}
        </table>
        <p style="margin:24px 0 0;">
          <a href="${escape(link)}" style="display:inline-block; background:#113972; color:#ffffff;
             text-decoration:none; font-weight:700; padding:13px 26px; border-radius:12px;">افتح الطلب</a>
        </p>
      </td></tr>
      <tr><td style="padding:16px 24px; background:#F4F7FB; color:#5B6B82; font-size:13px;">
        الرسالة دي جاية من موقع أكاديمية Thinkera.
      </td></tr>
    </table>
  </td></tr>
</table>
</body></html>`

    const lines = [
      title,
      `الاسم: ${doc.name || '-'}`,
      `البريد: ${doc.email || '-'}`,
      `الموبايل: ${doc.phone || '-'}`,
      `الصفة: ${doc.role || '-'}`,
      doc.note ? `السؤال: ${doc.note}` : '',
      '',
      link,
    ].filter(Boolean)

    await payload.sendEmail({
      to,
      // One fixed subject, so the academy can filter and label these in a mail client, and so a request never
      // arrives under a subject built out of whatever a stranger typed into the name box. The visitor's name
      // is the first thing in the body and the first row of the table.
      subject: 'Thinkera Interest Request',
      text: lines.join('\n'),
      html: body,
    })
    payload.logger.info({ msg: 'lead notification sent', to, lead: doc.id })
  } catch (error) {
    // The request is saved either way; losing the mail must not lose the lead.
    payload.logger.error({ msg: 'lead notification not sent', err: error })
  }
  return doc
}
