import type { BusinessProfile } from './site-settings.helper';
import { formatSmsMoney, sanitizeSmsText } from './sms-text.helper';

type PaymentLinkInfo = {
  url?: string | null;
  amount?: number;
  status?: string;
};

function formatMoney(amount: number) {
  return `GHS ${Number(amount || 0).toLocaleString('en-GH', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}

function formatSmsMessage(lines: string[]) {
  return sanitizeSmsText(lines.join('\n'));
}

function formatDateLabel(date?: string) {
  if (!date) return '';
  if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
    const parsed = new Date(`${date}T12:00:00`);
    if (Number.isNaN(parsed.getTime())) return date;
    return parsed.toLocaleDateString('en-GB', {
      weekday: 'long',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    });
  }
  return date;
}

function firstName(fullName?: string) {
  return String(fullName || '').trim().split(/\s+/)[0] || 'there';
}

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

function buildServiceSummary(appointment: Record<string, unknown>) {
  const lineItems = Array.isArray(appointment.lineItems) ? appointment.lineItems : [];
  if (lineItems.length) {
    return lineItems.map((item: Record<string, unknown>) => String(item.name || '')).join(', ');
  }
  return String(appointment.service || '');
}

function paymentStatusLabel(status?: string) {
  return String(status || 'UNPAID').replace(/_/g, ' ');
}

export function buildBookingReference(appointmentId: unknown) {
  if (!appointmentId) return '';
  return `MJL-${String(appointmentId).slice(-6).toUpperCase()}`;
}

export function resolveShareablePaymentLink(paymentLink?: PaymentLinkInfo | null) {
  if (!paymentLink?.url) return null;
  if (paymentLink.status === 'PAID') return null;
  return paymentLink;
}

type MessageContext = {
  appointment: Record<string, unknown>;
  business: BusinessProfile;
  paymentLink?: PaymentLinkInfo | null;
  reference?: string;
};

function paymentLinkSmsLines(paymentLink?: PaymentLinkInfo | null) {
  const link = resolveShareablePaymentLink(paymentLink);
  if (!link?.url) return [];

  const amount = Number(link.amount || 0);
  if (amount > 0) {
    return ['', `Pay ${formatSmsMoney(amount)}.`, link.url];
  }
  return ['', 'Pay online.', link.url];
}

function paymentLinkEmailLines(paymentLink?: PaymentLinkInfo | null) {
  const link = resolveShareablePaymentLink(paymentLink);
  if (!link?.url) return [];

  const amount = Number(link.amount || 0);
  if (amount > 0) {
    return [
      '',
      'Payment',
      '-------',
      `Amount due: ${formatMoney(amount)}`,
      `Secure payment link: ${link.url}`,
    ];
  }
  return ['', 'Payment', '-------', `Secure payment link: ${link.url}`];
}

export function buildBookingConfirmationSms({
  appointment,
  business,
  paymentLink,
  reference,
}: MessageContext) {
  const lines = [
    business.name,
    'Booking Confirmed',
    '',
    `Hi ${firstName(String(appointment.fullName))},`,
    '',
    `Service. ${buildServiceSummary(appointment)}`,
    `Date. ${formatDateLabel(String(appointment.date || ''))}`,
    `Time. ${appointment.time}`,
  ];

  if (reference) lines.push(`Ref. ${reference}`);
  lines.push(...paymentLinkSmsLines(paymentLink));
  lines.push('', 'Questions.', `Call ${business.phone}`, business.email);

  return formatSmsMessage(lines);
}

export function buildBookingConfirmationEmailText({
  appointment,
  business,
  paymentLink,
  reference,
}: MessageContext) {
  const lines = [
    `Dear ${firstName(String(appointment.fullName))},`,
    '',
    `Thank you for booking with ${business.name}. Your appointment is confirmed.`,
    '',
    'Appointment Details',
    '-------------------',
    `Service: ${buildServiceSummary(appointment)}`,
    `Date: ${formatDateLabel(String(appointment.date || ''))}`,
    `Time: ${appointment.time}`,
  ];

  if (reference) lines.push(`Reference: ${reference}`);
  if (appointment.notes) lines.push(`Notes: ${appointment.notes}`);
  lines.push(...paymentLinkEmailLines(paymentLink));
  lines.push(
    '',
    'Need to reschedule or have questions?',
    `Phone: ${business.phone}`,
    `Email: ${business.email}`,
    '',
    'We look forward to welcoming you.',
    '',
    `Warm regards,`,
    business.name,
    business.location,
    `${business.phone} · ${business.email}`,
  );

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

export function buildBookingConfirmationEmailHtml(ctx: MessageContext) {
  const { appointment, business, paymentLink, reference } = ctx;
  const link = resolveShareablePaymentLink(paymentLink);
  const serviceSummary = buildServiceSummary(appointment);
  const dateLabel = formatDateLabel(String(appointment.date || ''));
  const greeting = firstName(String(appointment.fullName));

  const paymentBlock = link?.url
    ? `<div style="margin:24px 0;padding:18px 20px;border:1px solid #eee7dc;border-radius:10px;background:#fcfaf7;">
        <p style="margin:0 0 8px;font-size:11px;letter-spacing:0.14em;text-transform:uppercase;color:#8a8175;">Payment</p>
        ${Number(link.amount || 0) > 0 ? `<p style="margin:0 0 12px;font-size:15px;color:#1a1a1a;">Amount due: <strong>${formatMoney(Number(link.amount || 0))}</strong></p>` : ''}
        <a href="${link.url}" style="display:inline-block;padding:12px 20px;background:#b8860b;color:#fff;text-decoration:none;border-radius:8px;font-size:14px;font-weight:600;">Pay Securely Online</a>
      </div>`
    : '';

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Booking Confirmed — ${business.name}</title>
</head>
<body style="margin:0;padding:32px 20px;font-family:Helvetica,Arial,sans-serif;background:#faf9f7;color:#1a1a1a;line-height:1.6;">
  <div style="max-width:620px;margin:0 auto;background:#fff;border:1px solid #ece7df;border-radius:12px;overflow:hidden;">
    <div style="padding:28px 32px;background:linear-gradient(135deg,#fff 0%,#faf6ef 100%);border-bottom:1px solid #f0ebe3;">
      <p style="margin:0;font-family:Georgia,'Times New Roman',serif;font-size:26px;color:#b8860b;">${business.name}</p>
      <p style="margin:8px 0 0;font-size:12px;letter-spacing:0.16em;text-transform:uppercase;color:#8a8175;">Booking Confirmed</p>
    </div>
    <div style="padding:28px 32px;">
      <p style="margin:0 0 16px;">Dear ${greeting},</p>
      <p style="margin:0 0 24px;">Thank you for choosing ${business.name}. We are delighted to confirm your appointment.</p>
      <div style="padding:18px 20px;border:1px solid #eee7dc;border-radius:10px;background:#fcfaf7;">
        <p style="margin:0 0 8px;font-size:11px;letter-spacing:0.14em;text-transform:uppercase;color:#8a8175;">Appointment Details</p>
        <p style="margin:0 0 6px;"><strong>${serviceSummary}</strong></p>
        <p style="margin:0 0 4px;color:#666;">${dateLabel}</p>
        <p style="margin:0;color:#666;">${appointment.time}</p>
        ${reference ? `<p style="margin:12px 0 0;font-size:13px;color:#666;">Reference: <strong>${reference}</strong></p>` : ''}
        ${appointment.notes ? `<p style="margin:12px 0 0;font-size:13px;color:#666;">Notes: ${escapeHtml(appointment.notes)}</p>` : ''}
      </div>
      ${paymentBlock}
      <p style="margin:24px 0 0;">If you need to reschedule or have any questions, please contact us at <a href="tel:${business.phone.replace(/\s/g, '')}" style="color:#b8860b;">${business.phone}</a> or <a href="mailto:${business.email}" style="color:#b8860b;">${business.email}</a>.</p>
      <p style="margin:16px 0 0;">We look forward to seeing you.</p>
      <p style="margin:24px 0 0;">Warm regards,<br><strong>${business.name}</strong><br>${business.location}</p>
    </div>
    <div style="padding:18px 32px;border-top:1px solid #f0ebe3;background:#fcfaf7;font-size:12px;color:#666;">
      <p style="margin:0;">${business.phone} · ${business.email} · ${business.website}</p>
    </div>
  </div>
</body>
</html>`;
}

export function buildDocumentShareSms(
  type: 'invoice' | 'receipt',
  { appointment, business, paymentLink }: MessageContext
) {
  const number = type === 'invoice' ? appointment.invoiceNumber : appointment.receiptNumber;
  const title = type === 'invoice' ? 'Invoice' : 'Receipt';
  const amountDue = Number(appointment.amountDue || 0);
  const amountPaid = Number(appointment.amountPaid || 0);
  const balance = Math.max(amountDue - amountPaid, 0);

  const lines = [
    business.name,
    `${title} ${number}`,
    '',
    `Hi ${firstName(String(appointment.fullName))},`,
    '',
    `Service. ${buildServiceSummary(appointment)}`,
    `Appt. ${formatDateLabel(String(appointment.date || ''))} at ${appointment.time}`,
  ];

  if (type === 'invoice') {
    lines.push(`Due. ${formatSmsMoney(amountDue)}`, `Paid. ${formatSmsMoney(amountPaid)}`);
    if (balance > 0) lines.push(`Balance. ${formatSmsMoney(balance)}`);
  } else {
    lines.push(`Paid. ${formatSmsMoney(amountPaid)}`, `Status. ${paymentStatusLabel(String(appointment.paymentStatus || ''))}`);
  }

  lines.push(...paymentLinkSmsLines(paymentLink));
  lines.push('', business.name, `${business.phone}. ${business.email}`);

  return formatSmsMessage(lines);
}

export function buildDocumentShareEmailText(
  type: 'invoice' | 'receipt',
  { appointment, business, paymentLink }: MessageContext
) {
  const number = type === 'invoice' ? appointment.invoiceNumber : appointment.receiptNumber;
  const title = type === 'invoice' ? 'Invoice' : 'Receipt';
  const amountDue = Number(appointment.amountDue || 0);
  const amountPaid = Number(appointment.amountPaid || 0);
  const amountRefunded = Number(appointment.amountRefunded || 0);
  const balance = Math.max(amountDue - amountPaid, 0);

  const lines = [
    `Dear ${firstName(String(appointment.fullName))},`,
    '',
    `Please find your ${title.toLowerCase()} details from ${business.name} below.`,
    '',
    `${title} Number: ${number}`,
    `Service: ${buildServiceSummary(appointment)}`,
    `Appointment: ${formatDateLabel(String(appointment.date || ''))} at ${appointment.time}`,
  ];

  if (type === 'invoice') {
    lines.push(
      `Amount due: ${formatMoney(amountDue)}`,
      `Amount paid: ${formatMoney(amountPaid)}`,
    );
    if (amountRefunded > 0) lines.push(`Refunded: ${formatMoney(amountRefunded)}`);
    if (balance > 0) lines.push(`Balance due: ${formatMoney(balance)}`);
  } else {
    lines.push(
      `Amount paid: ${formatMoney(amountPaid)}`,
      `Payment status: ${paymentStatusLabel(String(appointment.paymentStatus || ''))}`,
    );
    if (amountRefunded > 0) lines.push(`Amount refunded: ${formatMoney(amountRefunded)}`);
  }

  lines.push(...paymentLinkEmailLines(paymentLink));
  lines.push(
    '',
    'If you have any questions, we are happy to help.',
    `Phone: ${business.phone}`,
    `Email: ${business.email}`,
    '',
    'Thank you for choosing us.',
    '',
    `Warm regards,`,
    business.name,
    business.location,
    `${business.phone} · ${business.email}`,
  );

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

export function buildDocumentShareEmailHtml(
  type: 'invoice' | 'receipt',
  { appointment, business, paymentLink }: MessageContext
) {
  const number = type === 'invoice' ? appointment.invoiceNumber : appointment.receiptNumber;
  const title = type === 'invoice' ? 'Invoice' : 'Receipt';
  const amountDue = Number(appointment.amountDue || 0);
  const amountPaid = Number(appointment.amountPaid || 0);
  const amountRefunded = Number(appointment.amountRefunded || 0);
  const balance = Math.max(amountDue - amountPaid, 0);
  const greeting = firstName(String(appointment.fullName));
  const serviceSummary = buildServiceSummary(appointment);
  const dateLabel = formatDateLabel(String(appointment.date || ''));
  const link = resolveShareablePaymentLink(paymentLink);

  const amountRows =
    type === 'invoice'
      ? `
        <tr><td style="padding:8px 0;color:#666;">Amount due</td><td style="padding:8px 0;text-align:right;font-weight:600;">${formatMoney(amountDue)}</td></tr>
        <tr><td style="padding:8px 0;color:#666;">Amount paid</td><td style="padding:8px 0;text-align:right;font-weight:600;">${formatMoney(amountPaid)}</td></tr>
        ${amountRefunded > 0 ? `<tr><td style="padding:8px 0;color:#666;">Refunded</td><td style="padding:8px 0;text-align:right;font-weight:600;">${formatMoney(amountRefunded)}</td></tr>` : ''}
        ${balance > 0 ? `<tr><td style="padding:8px 0;color:#b8860b;font-weight:600;">Balance due</td><td style="padding:8px 0;text-align:right;font-weight:700;color:#b8860b;">${formatMoney(balance)}</td></tr>` : ''}
      `
      : `
        <tr><td style="padding:8px 0;color:#666;">Amount paid</td><td style="padding:8px 0;text-align:right;font-weight:600;">${formatMoney(amountPaid)}</td></tr>
        ${amountRefunded > 0 ? `<tr><td style="padding:8px 0;color:#666;">Refunded</td><td style="padding:8px 0;text-align:right;font-weight:600;">${formatMoney(amountRefunded)}</td></tr>` : ''}
        <tr><td style="padding:8px 0;color:#666;">Status</td><td style="padding:8px 0;text-align:right;font-weight:600;">${paymentStatusLabel(String(appointment.paymentStatus || ''))}</td></tr>
      `;

  const paymentBlock = link?.url
    ? `<div style="margin:24px 0;padding:18px 20px;border:1px solid #eee7dc;border-radius:10px;background:#fcfaf7;">
        <p style="margin:0 0 8px;font-size:11px;letter-spacing:0.14em;text-transform:uppercase;color:#8a8175;">Payment</p>
        ${Number(link.amount || 0) > 0 ? `<p style="margin:0 0 12px;font-size:15px;color:#1a1a1a;">Amount due: <strong>${formatMoney(Number(link.amount || 0))}</strong></p>` : ''}
        <a href="${link.url}" style="display:inline-block;padding:12px 20px;background:#b8860b;color:#fff;text-decoration:none;border-radius:8px;font-size:14px;font-weight:600;">Pay Securely Online</a>
      </div>`
    : '';

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>${title} ${number} — ${business.name}</title>
</head>
<body style="margin:0;padding:32px 20px;font-family:Helvetica,Arial,sans-serif;background:#faf9f7;color:#1a1a1a;line-height:1.6;">
  <div style="max-width:620px;margin:0 auto;background:#fff;border:1px solid #ece7df;border-radius:12px;overflow:hidden;">
    <div style="padding:28px 32px;background:linear-gradient(135deg,#fff 0%,#faf6ef 100%);border-bottom:1px solid #f0ebe3;">
      <p style="margin:0;font-family:Georgia,'Times New Roman',serif;font-size:26px;color:#b8860b;">${business.name}</p>
      <p style="margin:8px 0 0;font-size:12px;letter-spacing:0.16em;text-transform:uppercase;color:#8a8175;">${title} ${escapeHtml(number)}</p>
    </div>
    <div style="padding:28px 32px;">
      <p style="margin:0 0 16px;">Dear ${escapeHtml(greeting)},</p>
      <p style="margin:0 0 24px;">Please find your ${title.toLowerCase()} from ${business.name} below.</p>
      <div style="padding:18px 20px;border:1px solid #eee7dc;border-radius:10px;background:#fcfaf7;">
        <p style="margin:0 0 8px;font-size:11px;letter-spacing:0.14em;text-transform:uppercase;color:#8a8175;">Details</p>
        <p style="margin:0 0 6px;"><strong>${escapeHtml(serviceSummary)}</strong></p>
        <p style="margin:0 0 4px;color:#666;">${escapeHtml(dateLabel)}</p>
        <p style="margin:0;color:#666;">${escapeHtml(String(appointment.time || ''))}</p>
        <table style="width:100%;margin-top:16px;border-collapse:collapse;">
          ${amountRows}
        </table>
      </div>
      ${paymentBlock}
      <p style="margin:24px 0 0;">If you have any questions, contact us at <a href="tel:${business.phone.replace(/\s/g, '')}" style="color:#b8860b;">${business.phone}</a> or <a href="mailto:${business.email}" style="color:#b8860b;">${business.email}</a>.</p>
      <p style="margin:16px 0 0;">Thank you for choosing ${business.name}.</p>
      <p style="margin:24px 0 0;">Warm regards,<br><strong>${business.name}</strong><br>${business.location}</p>
    </div>
    <div style="padding:18px 32px;border-top:1px solid #f0ebe3;background:#fcfaf7;font-size:12px;color:#666;">
      <p style="margin:0;">${business.phone} · ${business.email} · ${business.website}</p>
    </div>
  </div>
</body>
</html>`;
}
