export interface AuditorScheduleRow {
  audit_code: string;
  category: string;        // e.g. "Initial", "Surveillance", "Re-Certification"
  company_name: string;
  standards: string;       // comma-separated
  accreditation: string;
  stage: string;           // e.g. "Stage 1"
  mode: string;            // e.g. "Onsite", "Online", "Hybrid"
  coordinator: string;
  time_label: string;      // e.g. "11.00AM"
  status: string;          // e.g. "Pending", "Cancelled", "Completed"
  is_this_audit: boolean;  // true → highlight the row in green
}

export interface AuditorAssignmentEmailContext {
  auditorName: string;
  auditorEmail?: string;
  scheduleDateLabel: string;   // e.g. "20th May 2026"
  coordinatorName: string;
  clientGroup?: string;

  // This audit
  auditCode: string;
  companyName: string;
  auditeeName: string;
  auditeeContact: string;
  auditeeEmail: string;
  dateTimeOfAudit: string;     // e.g. "20th May 2026 at 12.02 PM (Onsite Audit)"
  standards: string;
  certification: string;
  accreditation: string;
  locationDetails: string;
  marketingRemarks?: string;
  coordinatorRemarks?: string;
  ctaUrl?: string;

  // Full day grid — all audits assigned to this auditor on the same date
  scheduleRows: AuditorScheduleRow[];
}

const BRAND = '#4a0080';
const BRAND_LIGHT = '#f4eefb';
const ACCENT = '#16a34a';
const ACCENT_SOFT = '#dcfce7';
const INK = '#0f172a';
const MUTED = '#64748b';
const BORDER = '#e2e8f0';
const GOLD = '#c9a44a';
const HIGHLIGHT_ROW = '#fff4e6';
const HIGHLIGHT_BORDER = '#f59e0b';

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

function statusBadge(status: string): string {
  const s = (status || '').toLowerCase();
  let bg = '#dbeafe';
  let fg = '#1e3a8a';
  let label = status || 'Pending';
  if (s.includes('cancel')) { bg = '#fee2e2'; fg = '#991b1b'; label = 'Cancelled'; }
  else if (s.includes('complete')) { bg = '#dcfce7'; fg = '#166534'; label = 'Completed'; }
  else if (s.includes('schedul')) { bg = '#dcfce7'; fg = '#166534'; label = 'Scheduled'; }
  else if (s.includes('confirm')) { bg = '#dcfce7'; fg = '#166534'; label = 'Scheduled'; }
  else if (s.includes('reschedul')) { bg = '#fef3c7'; fg = '#92400e'; label = 'Rescheduled'; }
  else if (s.includes('pending')) { bg = '#fef3c7'; fg = '#92400e'; label = 'Pending'; }
  return `<span style="display:inline-block;background:${bg};color:${fg};font-size:11px;font-weight:600;padding:3px 9px;border-radius:10px;white-space:nowrap;">${escapeHtml(label)}</span>`;
}

function detailRow(label: string, value: string, alt: boolean): string {
  return `
    <tr>
      <td style="padding:11px 16px;background:${alt ? '#f8fafc' : '#ffffff'};border-bottom:1px solid ${BORDER};font-size:12px;font-weight:600;color:${MUTED};text-transform:uppercase;letter-spacing:0.04em;width:38%;vertical-align:top;">${escapeHtml(label)}</td>
      <td style="padding:11px 16px;background:${alt ? '#f8fafc' : '#ffffff'};border-bottom:1px solid ${BORDER};font-size:14px;font-weight:600;color:${INK};vertical-align:top;word-break:break-word;">${value}</td>
    </tr>
  `;
}

function buildScheduleGrid(rows: AuditorScheduleRow[]): string {
  if (!rows?.length) return '';

  const head = `
    <tr style="background:${BRAND};">
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">#</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Audit Code</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Category</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Company</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Standard</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Accr.</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Stage</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Mode</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Time</th>
      <th style="padding:10px 8px;font-size:11px;color:#ffffff;font-weight:700;letter-spacing:0.04em;text-transform:uppercase;text-align:left;">Status</th>
    </tr>
  `;

  const body = rows.map((r, i) => {
    const isHighlight = r.is_this_audit;
    const rowBg = isHighlight ? HIGHLIGHT_ROW : (i % 2 === 0 ? '#ffffff' : '#f8fafc');
    const borderLeft = isHighlight ? `border-left:3px solid ${HIGHLIGHT_BORDER};` : '';
    return `
      <tr style="background:${rowBg};${borderLeft}">
        <td style="padding:10px 8px;font-size:13px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;font-weight:${isHighlight ? '700' : '500'};">${i + 1}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;font-family:'Courier New',monospace;font-weight:${isHighlight ? '700' : '600'};">${escapeHtml(r.audit_code)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;">${escapeHtml(r.category)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;font-weight:${isHighlight ? '700' : '600'};">${escapeHtml(r.company_name)}</td>
        <td style="padding:10px 8px;font-size:11px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;line-height:1.5;">${escapeHtml(r.standards)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;">${escapeHtml(r.accreditation)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;">${escapeHtml(r.stage)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;">${escapeHtml(r.mode)}</td>
        <td style="padding:10px 8px;font-size:12px;color:${INK};border-bottom:1px solid ${BORDER};vertical-align:top;font-weight:600;">${escapeHtml(r.time_label)}</td>
        <td style="padding:10px 8px;border-bottom:1px solid ${BORDER};vertical-align:top;">${statusBadge(r.status)}</td>
      </tr>
    `;
  }).join('');

  return `
    <div style="margin:28px 0 8px;">
      <div style="font-size:13px;font-weight:700;color:${BRAND};text-transform:uppercase;letter-spacing:0.06em;margin-bottom:10px;text-align:center;">
        Your audit schedule for the day
      </div>
      <div style="overflow-x:auto;border:1px solid ${BORDER};border-radius:8px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;">
          <thead>${head}</thead>
          <tbody>${body}</tbody>
        </table>
      </div>
      <div style="margin-top:8px;font-size:11px;color:${MUTED};font-style:italic;text-align:center;">
        Highlighted row = the newly scheduled audit you have been assigned to.
      </div>
    </div>
  `;
}

export function buildAuditorAssignmentEmail(ctx: AuditorAssignmentEmailContext): string {
  const detailRows: Array<[string, string]> = [
    ['Audit Code', `<span style="font-family:'Courier New',monospace;">${escapeHtml(ctx.auditCode)}</span>`],
    ['Company', escapeHtml(ctx.companyName)],
    ['Auditee', escapeHtml(ctx.auditeeName)],
    ['Contact No', escapeHtml(ctx.auditeeContact)],
    ['Email', `<span style="color:${BRAND};">${escapeHtml(ctx.auditeeEmail)}</span>`],
    ['Standard(s)', escapeHtml(ctx.standards)],
    ['Date & Time', escapeHtml(ctx.dateTimeOfAudit)],
    ['Location', escapeHtml(ctx.locationDetails)],
    ['Certification', escapeHtml(ctx.certification)],
    ['Accreditation', escapeHtml(ctx.accreditation)],
  ];

  const detailRowsHtml = detailRows
    .map(([k, v], i) => detailRow(k, v, i % 2 === 1))
    .join('');

  const marketingRemarksHtml = ctx.marketingRemarks
    ? `
      <div style="background:${BRAND_LIGHT};border-left:3px solid ${BRAND};padding:14px 16px;margin:18px 0;">
        <div style="font-size:11px;font-weight:700;color:${BRAND};text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px;">Marketing remarks</div>
        <div style="font-size:13px;color:${INK};line-height:1.6;">${escapeHtml(ctx.marketingRemarks)}</div>
      </div>
    `
    : '';

  const coordinatorRemarksHtml = ctx.coordinatorRemarks
    ? `
      <div style="background:${ACCENT_SOFT};border-left:3px solid ${ACCENT};padding:14px 16px;margin:18px 0;">
        <div style="font-size:11px;font-weight:700;color:${ACCENT};text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px;">Notes from coordinator</div>
        <div style="font-size:13px;color:${INK};line-height:1.6;">${escapeHtml(ctx.coordinatorRemarks)}</div>
      </div>
    `
    : '';

  const ctaHtml = ctx.ctaUrl
    ? `
      <table role="presentation" cellpadding="0" cellspacing="0" align="center" style="margin:26px auto 6px;">
        <tr>
          <td>
            <!--[if mso]>
              <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word"
                href="${escapeHtml(ctx.ctaUrl)}" style="height:46px;v-text-anchor:middle;width:240px;" arcsize="13%" stroke="f" fillcolor="${BRAND}">
                <w:anchorlock/>
                <center style="color:#ffffff;font-family:'Segoe UI',Arial,sans-serif;font-size:14px;font-weight:600;">View Schedule</center>
              </v:roundrect>
            <![endif]-->
            <!--[if !mso]><!-- -->
            <a href="${escapeHtml(ctx.ctaUrl)}" style="display:inline-block;padding:13px 34px;background:${BRAND};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;font-size:14px;font-family:'Segoe UI',Arial,sans-serif;">View Schedule &rarr;</a>
            <!--<![endif]-->
          </td>
        </tr>
      </table>
    `
    : '';

  return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Lead Auditor Assignment</title>
<!--[if mso]>
<style type="text/css">
  table, td, div, p, a { font-family: 'Segoe UI', Arial, sans-serif !important; }
</style>
<![endif]-->
</head>
<body style="margin:0;padding:0;background:#eef0f2;font-family:'Segoe UI',Arial,sans-serif;-webkit-font-smoothing:antialiased;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#eef0f2;">
  <tr>
    <td align="center" style="padding:24px 12px;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="width:100%;max-width:760px;background:#ffffff;border-radius:10px;overflow:hidden;border:1px solid ${BORDER};">

        <tr>
          <td style="background:${BRAND};padding:24px 32px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
              <tr>
                <td style="font-family:'Segoe UI',Arial,sans-serif;color:#ffffff;font-size:18px;font-weight:700;">
                  Quality Registrar Systems
                </td>
                <td align="right" style="font-family:'Segoe UI',Arial,sans-serif;">
                  <span style="display:inline-block;background:${ACCENT};color:#ffffff;font-size:11px;font-weight:700;padding:5px 12px;border-radius:20px;text-transform:uppercase;letter-spacing:0.05em;">
                    Lead Auditor Assignment
                  </span>
                </td>
              </tr>
            </table>
          </td>
        </tr>

        <tr>
          <td style="padding:28px 32px 8px;font-family:'Segoe UI',Arial,sans-serif;">
            <p style="margin:0 0 14px;font-size:15px;color:${INK};">Dear <strong>${escapeHtml(ctx.auditorName)}</strong>,</p>
            <p style="margin:0 0 18px;font-size:14px;color:${MUTED};line-height:1.7;">
              You have been assigned as <strong style="color:${INK};">Lead Auditor</strong> for the following audit on
              <strong style="color:${INK};">${escapeHtml(ctx.scheduleDateLabel)}</strong>.
              Please review the audit details below and confirm your availability with the coordinator.
            </p>
          </td>
        </tr>

        <tr>
          <td style="padding:0 32px 8px;font-family:'Segoe UI',Arial,sans-serif;">
            <div style="font-size:12px;font-weight:700;color:${BRAND};text-transform:uppercase;letter-spacing:0.06em;margin-bottom:10px;">This audit</div>
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid ${BORDER};border-radius:8px;overflow:hidden;">
              ${detailRowsHtml}
            </table>
            ${marketingRemarksHtml}
            ${coordinatorRemarksHtml}
            ${ctaHtml}
          </td>
        </tr>

        <tr>
          <td style="padding:0 32px;font-family:'Segoe UI',Arial,sans-serif;">
            ${buildScheduleGrid(ctx.scheduleRows)}
          </td>
        </tr>

        <tr>
          <td style="background:#f8fafc;border-top:1px solid ${BORDER};padding:14px 32px;font-family:'Segoe UI',Arial,sans-serif;">
            <p style="margin:0;font-size:11px;color:#94a3b8;line-height:1.6;">
              Quality Registrar Systems also collaborates with IAS, EIAC, and other international accreditation bodies.
            </p>
            <p style="margin:6px 0 0;font-size:11px;color:#94a3b8;">
              &copy; ${new Date().getFullYear()} Quality Registrar Systems. All rights reserved.
            </p>
          </td>
        </tr>

      </table>
    </td>
  </tr>
</table>
</body>
</html>`;
}