/**
 * Staff Contact Notification Emails Service
 *
 * Handles email notifications to staff when new contact form submissions are received.
 */

import { sendEmail } from '../email';
import { logger } from '../logger';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'https://mawidi.com';
const STAFF_NOTIFICATION_EMAILS = process.env.STAFF_NOTIFICATION_EMAILS?.split(',').filter(Boolean) || ['admin@mawidi.com'];

interface ContactSubmissionData {
  id: string;
  name: string;
  email: string;
  phone?: string;
  company?: string | null;
  topic: string;
  message: string;
  preferred_language: 'ar' | 'en';
  submission_language: 'ar' | 'en';
}

/**
 * Send notification to staff about new contact form submission
 */
export async function sendNewContactNotification(
  contact: ContactSubmissionData
): Promise<{ success: boolean; error?: string }> {
  try {
    // Use configured staff notification emails from environment
    const recipientEmails = STAFF_NOTIFICATION_EMAILS;

    if (recipientEmails.length === 0) {
      logger.warn('[Staff Contact Email] No recipient emails configured');
      return { success: false, error: 'No notification recipients configured' };
    }

    const template = generateContactNotificationEmail(contact);

    // Send to all recipients
    const results = await Promise.allSettled(
      recipientEmails.map(email => sendEmail(email, template))
    );

    const successCount = results.filter(
      (r): r is PromiseFulfilledResult<boolean> => r.status === 'fulfilled' && Boolean(r.value)
    ).length;

    if (successCount === 0) {
      logger.error('[Staff Contact Email] All notifications failed', {
        contactId: contact.id,
        recipientCount: recipientEmails.length,
      });
      return { success: false, error: 'Failed to send notifications to any staff member' };
    }

    logger.info('[Staff Contact Email] Notifications sent', {
      contactId: contact.id,
      successCount,
      totalRecipients: recipientEmails.length,
    });

    return { success: true };
  } catch (error) {
    logger.error('[Staff Contact Email] Failed to send notification', { error });
    return { success: false, error: 'Internal error sending notification' };
  }
}

/**
 * Generate contact notification email template for staff
 */
function generateContactNotificationEmail(contact: ContactSubmissionData) {
  const staffDashboardUrl = `${BASE_URL}/staff/dashboard?tab=contacts`;
  const isArabicSubmission = contact.submission_language === 'ar';

  const subject = `🔔 New Contact Submission: ${contact.topic}`;

  const html = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${subject}</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f3f4f6;">
  <div style="max-width: 600px; margin: 0 auto; padding: 40px 20px;">
    <div style="background: white; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);">
      <!-- Header -->
      <div style="background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); padding: 30px; text-align: center;">
        <h1 style="margin: 0; color: white; font-size: 24px; font-weight: 600;">📩 New Contact Form Submission</h1>
      </div>

      <!-- Content -->
      <div style="padding: 30px;">
        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          A new contact form submission has been received and requires attention.
        </p>

        <!-- Contact Details Card -->
        <div style="background: #f9fafb; border-radius: 12px; padding: 20px; margin: 20px 0;">
          <table style="width: 100%; border-collapse: collapse;">
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; width: 120px; vertical-align: top;">Name:</td>
              <td style="padding: 10px 0; color: #111827; font-size: 14px; font-weight: 600;">${escapeHtml(contact.name)}</td>
            </tr>
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; vertical-align: top;">Email:</td>
              <td style="padding: 10px 0; color: #111827; font-size: 14px;">
                <a href="mailto:${escapeHtml(contact.email)}" style="color: #3b82f6; text-decoration: none;">
                  ${escapeHtml(contact.email)}
                </a>
              </td>
            </tr>
            ${contact.phone ? `
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; vertical-align: top;">Phone:</td>
              <td style="padding: 10px 0; color: #111827; font-size: 14px;">${escapeHtml(contact.phone)}</td>
            </tr>
            ` : ''}
            ${contact.company ? `
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; vertical-align: top;">Company:</td>
              <td style="padding: 10px 0; color: #111827; font-size: 14px;">${escapeHtml(contact.company)}</td>
            </tr>
            ` : ''}
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; vertical-align: top;">Topic:</td>
              <td style="padding: 10px 0;">
                <span style="display: inline-block; background: #dbeafe; color: #1e40af; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500;">
                  ${escapeHtml(contact.topic)}
                </span>
              </td>
            </tr>
            <tr>
              <td style="padding: 10px 0; color: #6b7280; font-size: 14px; vertical-align: top;">Language:</td>
              <td style="padding: 10px 0; color: #111827; font-size: 14px;">
                ${isArabicSubmission ? '🇸🇦 Arabic' : '🇬🇧 English'}
              </td>
            </tr>
          </table>
        </div>

        <!-- Message Preview -->
        <div style="margin: 20px 0;">
          <h3 style="margin: 0 0 12px; color: #374151; font-size: 14px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;">Message</h3>
          <div style="background: #fefce8; border: 1px solid #fef08a; border-radius: 12px; padding: 20px; ${isArabicSubmission ? 'direction: rtl; text-align: right;' : ''}">
            <p style="margin: 0; color: #713f12; font-size: 14px; line-height: 1.8; white-space: pre-wrap;">
${escapeHtml(contact.message)}
            </p>
          </div>
        </div>

        <!-- CTA Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="${staffDashboardUrl}" style="display: inline-block; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 14px 32px; text-decoration: none; border-radius: 10px; font-weight: 600; font-size: 16px;">
            View in Dashboard
          </a>
        </div>

        <!-- Quick Actions -->
        <div style="text-align: center; margin: 20px 0;">
          <a href="mailto:${escapeHtml(contact.email)}?subject=Re: ${encodeURIComponent(contact.topic)}" style="color: #3b82f6; text-decoration: none; font-size: 14px; margin: 0 10px;">
            📧 Reply via Email
          </a>
          ${contact.phone ? `
          <span style="color: #d1d5db;">|</span>
          <a href="tel:${escapeHtml(contact.phone)}" style="color: #3b82f6; text-decoration: none; font-size: 14px; margin: 0 10px;">
            📞 Call
          </a>
          ` : ''}
        </div>
      </div>

      <!-- Footer -->
      <div style="padding: 20px 30px; background: #f9fafb; text-align: center;">
        <p style="margin: 0; color: #9ca3af; font-size: 12px;">
          Submission ID: ${contact.id.slice(0, 12)}
        </p>
        <p style="margin: 8px 0 0; color: #9ca3af; font-size: 12px;">
          This is an automated notification from Mawidi CRM
        </p>
      </div>
    </div>
  </div>
</body>
</html>
`;

  const text = `
New Contact Form Submission

Name: ${contact.name}
Email: ${contact.email}
${contact.phone ? `Phone: ${contact.phone}` : ''}
${contact.company ? `Company: ${contact.company}` : ''}
Topic: ${contact.topic}
Language: ${isArabicSubmission ? 'Arabic' : 'English'}

Message:
${contact.message}

View in Dashboard: ${staffDashboardUrl}

---
Submission ID: ${contact.id.slice(0, 12)}
This is an automated notification from Mawidi CRM
`;

  return { subject, html, text };
}

/**
 * Escape HTML special characters to prevent XSS
 */
function escapeHtml(text: string): string {
  const htmlEscapes: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
  };
  return text.replace(/[&<>"']/g, char => htmlEscapes[char]);
}
