export interface MeetingInviteEmailContext {
  recipientName: string;
  meetingTitle: string;
  companyName?: string | null;
  /** the room code — shown as "Meeting ID" so it reads like Zoom */
  roomCode: string;
  joinUrl: string;
  /** only present for VERIFIED invites */
  passcode?: string;
  scheduledAt?: Date | string | null;
  hostName?: string | null;
  standards?: string | null;
  isRecorded?: boolean;
  expiresAt: Date | string;
  /** minutes the passcode stays valid */
  passcodeValidMinutes?: number;

  senderName?: string;
  senderTitle?: string;
  senderPhone?: string;
  senderEmail?: string;
  senderAddress?: string;
  senderWebsite?: string;
}

const fmtDateTime = (d?: Date | string | null): string => {
  if (!d) return 'To be confirmed';
  const date = new Date(d);
  if (isNaN(date.getTime())) return 'To be confirmed';

  const day = date.getDate();
  const suffix = (() => {
    const j = day % 10;
    const k = day % 100;
    if (j === 1 && k !== 11) return 'st';
    if (j === 2 && k !== 12) return 'nd';
    if (j === 3 && k !== 13) return 'rd';
    return 'th';
  })();

  const month = date.toLocaleString('en-US', { month: 'long' });
  const hh = date.getHours();
  const mm = String(date.getMinutes()).padStart(2, '0');
  const period = hh >= 12 ? 'PM' : 'AM';
  const hour12 = hh % 12 === 0 ? 12 : hh % 12;

  return `${day}${suffix} ${month} ${date.getFullYear()} at ${hour12}.${mm} ${period}`;
};

const fmtExpiry = (d: Date | string): string => {
  const date = new Date(d);
  const hh = date.getHours();
  const mm = String(date.getMinutes()).padStart(2, '0');
  const period = hh >= 12 ? 'PM' : 'AM';
  const hour12 = hh % 12 === 0 ? 12 : hh % 12;
  return `${hour12}.${mm} ${period}`;
};

/**
 * Deliberately plain. Meeting invites get forwarded, printed and read on
 * phones with images blocked — so the meeting id, passcode and link all
 * survive as text rather than living inside a graphic.
 */
export function buildMeetingInviteEmail(
  ctx: MeetingInviteEmailContext,
): string {
  const sender = {
    name: ctx.senderName ?? 'QRS Certification',
    title: ctx.senderTitle ?? '',
    phone: ctx.senderPhone ?? '026714302',
    email: ctx.senderEmail ?? 'account@qrs.ae',
    address:
      ctx.senderAddress ??
      'Office # 203 Nasser Tower, Saeed Bin Ahmed Al Otaiba St. Al Danah, Zone 1, Abu Dhabi, UAE',
    website: ctx.senderWebsite ?? 'www.qrsyst.com',
  };

  const passcodeBlock = ctx.passcode
    ? `
      <tr>
        <td style="padding:0 0 14px;">
          <div style="background:#fff8e6;border:1px solid #f0d999;border-radius:10px;padding:14px 16px;">
            <p style="margin:0;font-size:11px;color:#8a7a55;letter-spacing:1.2px;font-weight:700;">
              PASSCODE
            </p>
            <p style="margin:6px 0 0;font-size:28px;font-weight:700;color:#1a2333;letter-spacing:6px;font-family:'Courier New',monospace;">
              ${ctx.passcode}
            </p>
            <p style="margin:8px 0 0;font-size:11.5px;color:#8a7a55;line-height:1.5;">
              You will be asked for this after opening the link.
              It is valid for ${ctx.passcodeValidMinutes ?? 45} minutes —
              if it expires you can request a new one on the page.
            </p>
          </div>
        </td>
      </tr>`
    : '';

  const recordingNote = ctx.isRecorded
    ? `
      <p style="margin:18px 0 0;font-size:11.5px;color:#8a8f9c;line-height:1.6;">
        This meeting is recorded and transcribed for certification records.
        By joining, you consent to recording.
      </p>`
    : '';

  return `
<div style="font-family:'Segoe UI',Arial,sans-serif;max-width:600px;margin:0 auto;background:#ffffff;">

  <div style="background:linear-gradient(135deg,#0B7A43,#12A15A);padding:28px 32px;">
    <h1 style="color:#ffffff;font-size:19px;margin:0;font-weight:600;">
      Quality Registrar Systems
    </h1>
    <p style="color:rgba(255,255,255,0.85);margin:5px 0 0;font-size:13px;">
      Meeting invitation
    </p>
  </div>

  <div style="padding:30px 32px;">

    <p style="margin:0 0 6px;font-size:15px;color:#1a2333;">
      Dear ${ctx.recipientName},
    </p>
    <p style="margin:0 0 22px;font-size:13.5px;color:#5a6472;line-height:1.7;">
      You have been invited to join an online meeting${
        ctx.companyName ? ` for <strong>${ctx.companyName}</strong>` : ''
      }.
    </p>

    <table style="width:100%;border-collapse:collapse;">

      <tr>
        <td style="padding:0 0 14px;">
          <div style="background:#f7f9fa;border:1px solid #e3e8ee;border-radius:10px;padding:16px 18px;">
            <p style="margin:0 0 12px;font-size:15px;font-weight:600;color:#1a2333;">
              ${ctx.meetingTitle}
            </p>

            <table style="width:100%;border-collapse:collapse;font-size:13px;">
              <tr>
                <td style="padding:5px 0;color:#7a8496;width:38%;">When</td>
                <td style="padding:5px 0;color:#1a2333;font-weight:600;">
                  ${fmtDateTime(ctx.scheduledAt)}
                </td>
              </tr>
              ${
                ctx.hostName
                  ? `<tr>
                      <td style="padding:5px 0;color:#7a8496;">Host</td>
                      <td style="padding:5px 0;color:#1a2333;font-weight:600;">${ctx.hostName}</td>
                    </tr>`
                  : ''
              }
              ${
                ctx.standards
                  ? `<tr>
                      <td style="padding:5px 0;color:#7a8496;">Standards</td>
                      <td style="padding:5px 0;color:#1a2333;font-weight:600;">${ctx.standards}</td>
                    </tr>`
                  : ''
              }
              <tr>
                <td style="padding:5px 0;color:#7a8496;">Meeting ID</td>
                <td style="padding:5px 0;color:#1a2333;font-weight:700;font-family:'Courier New',monospace;letter-spacing:0.5px;">
                  ${ctx.roomCode}
                </td>
              </tr>
            </table>
          </div>
        </td>
      </tr>

      ${passcodeBlock}

      <tr>
        <td style="padding:4px 0 0;text-align:center;">
          <a href="${ctx.joinUrl}"
             style="display:inline-block;padding:14px 40px;background:#0B7A43;color:#ffffff;
                    text-decoration:none;border-radius:8px;font-weight:600;font-size:15px;">
            Join meeting
          </a>
          <p style="margin:12px 0 0;font-size:11.5px;color:#8a8f9c;">
            Or paste this link into your browser:
          </p>
          <p style="margin:4px 0 0;font-size:12px;">
            <a href="${ctx.joinUrl}" style="color:#0B7A43;word-break:break-all;">
              ${ctx.joinUrl}
            </a>
          </p>
        </td>
      </tr>

    </table>

    <p style="margin:22px 0 0;font-size:11.5px;color:#8a8f9c;line-height:1.6;">
      This invitation expires at ${fmtExpiry(ctx.expiresAt)}. It is personal to
      you — please do not forward it.
    </p>

    ${recordingNote}

    <div style="margin-top:26px;padding-top:18px;border-top:1px solid #e8ecf1;">
      <p style="margin:0;font-size:13px;color:#1a2333;font-weight:600;">
        ${sender.name}
      </p>
      ${
        sender.title
          ? `<p style="margin:2px 0 0;font-size:12px;color:#7a8496;">${sender.title}</p>`
          : ''
      }
      <p style="margin:8px 0 0;font-size:11.5px;color:#7a8496;line-height:1.7;">
        ${sender.phone}<br>
        <a href="mailto:${sender.email}" style="color:#0B7A43;">${sender.email}</a><br>
        ${sender.address}<br>
        <a href="https://${sender.website}" style="color:#0B7A43;">${sender.website}</a>
      </p>
    </div>

  </div>

  <div style="background:#f7f9fa;padding:14px 32px;border-top:1px solid #e8ecf1;">
    <p style="color:#a8aeb8;font-size:11px;margin:0;">
      © ${new Date().getFullYear()} Quality Registrar Systems.
    </p>
  </div>

</div>`;
}

/**
 * Plain-text version for WhatsApp and SMS.
 *
 * WhatsApp uses *asterisks* for bold. Kept short because a long message gets
 * truncated in the notification preview, and the link is the thing that
 * matters.
 */
export function buildMeetingInviteText(
  ctx: MeetingInviteEmailContext,
  channel: 'WHATSAPP' | 'SMS' = 'WHATSAPP',
): string {
  const bold = (s: string) => (channel === 'WHATSAPP' ? `*${s}*` : s);

  const lines = [
    bold('QRS meeting invitation'),
    '',
    ctx.meetingTitle,
  ];

  if (ctx.companyName) lines.push(ctx.companyName);
  lines.push('');
  lines.push(`When: ${fmtDateTime(ctx.scheduledAt)}`);
  lines.push(`Meeting ID: ${ctx.roomCode}`);
  if (ctx.passcode) lines.push(`Passcode: ${ctx.passcode}`);
  lines.push('');
  lines.push(`Join: ${ctx.joinUrl}`);

  if (ctx.isRecorded) {
    lines.push('');
    lines.push('This meeting is recorded for certification records.');
  }

  return lines.join('\n');
}
