/**
 * Support Ticket Email Notifications Service
 *
 * Handles email notifications for support ticket events:
 * - Staff replies to tickets
 * - Ticket status changes
 */

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

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'https://mawidi.com';

interface SupportEmailData {
  ticketId: string;
  ticketSubject: string;
  recipientEmail: string;
  recipientName: string;
  senderName: string;
  messagePreview: string;
  lang: 'ar' | 'en';
}

interface StatusChangeEmailData extends SupportEmailData {
  oldStatus: string;
  newStatus: string;
}

/**
 * Send notification when staff replies to a ticket
 */
export async function sendStaffReplyNotification(
  data: SupportEmailData
): Promise<{ success: boolean; error?: string }> {
  try {
    const template = generateStaffReplyEmail(data);
    const sent = await sendEmail(data.recipientEmail, template);

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    logger.info('[Support Email] Reply notification sent', {
      ticketId: data.ticketId,
      to: data.recipientEmail,
    });

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

/**
 * Send notification when ticket status changes
 */
export async function sendStatusChangeNotification(
  data: StatusChangeEmailData
): Promise<{ success: boolean; error?: string }> {
  try {
    const template = generateStatusChangeEmail(data);
    const sent = await sendEmail(data.recipientEmail, template);

    if (!sent) {
      return { success: false, error: 'Failed to send email' };
    }

    logger.info('[Support Email] Status change notification sent', {
      ticketId: data.ticketId,
      to: data.recipientEmail,
      oldStatus: data.oldStatus,
      newStatus: data.newStatus,
    });

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

/**
 * Generate staff reply notification email template
 */
function generateStaffReplyEmail(data: SupportEmailData) {
  const isAr = data.lang === 'ar';
  const ticketUrl = `${BASE_URL}/${data.lang}/dashboard?tab=support`;

  const subject = isAr
    ? `رد جديد على تذكرتك #${data.ticketId.slice(0, 8)}`
    : `New reply to your ticket #${data.ticketId.slice(0, 8)}`;

  const html = isAr
    ? `
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<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; direction: rtl;">
  <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, #10b981 0%, #059669 100%); padding: 30px; text-align: center;">
        <h1 style="margin: 0; color: white; font-size: 24px; font-weight: 600;">رد جديد على تذكرتك</h1>
      </div>

      <!-- Content -->
      <div style="padding: 30px;">
        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          مرحباً ${data.recipientName}،
        </p>

        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          تم الرد على تذكرتك "<strong>${data.ticketSubject}</strong>" من قبل ${data.senderName}.
        </p>

        <!-- Message Preview -->
        <div style="background: #f9fafb; border-radius: 12px; padding: 20px; margin: 20px 0; border-right: 4px solid #10b981;">
          <p style="margin: 0; color: #4b5563; font-size: 14px; line-height: 1.6;">
            ${data.messagePreview}
          </p>
        </div>

        <!-- CTA Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="${ticketUrl}" 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;">
            عرض التذكرة
          </a>
        </div>

        <p style="margin: 20px 0 0; color: #6b7280; font-size: 14px; line-height: 1.6;">
          إذا كنت بحاجة إلى مساعدة إضافية، يمكنك الرد على هذه التذكرة من لوحة التحكم الخاصة بك.
        </p>
      </div>

      <!-- Footer -->
      <div style="padding: 20px 30px; background: #f9fafb; text-align: center;">
        <p style="margin: 0; color: #9ca3af; font-size: 12px;">
          فريق دعم Mawidi
        </p>
      </div>
    </div>
  </div>
</body>
</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, #10b981 0%, #059669 100%); padding: 30px; text-align: center;">
        <h1 style="margin: 0; color: white; font-size: 24px; font-weight: 600;">New Reply to Your Ticket</h1>
      </div>

      <!-- Content -->
      <div style="padding: 30px;">
        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          Hello ${data.recipientName},
        </p>

        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          Your ticket "<strong>${data.ticketSubject}</strong>" has received a reply from ${data.senderName}.
        </p>

        <!-- Message Preview -->
        <div style="background: #f9fafb; border-radius: 12px; padding: 20px; margin: 20px 0; border-left: 4px solid #10b981;">
          <p style="margin: 0; color: #4b5563; font-size: 14px; line-height: 1.6;">
            ${data.messagePreview}
          </p>
        </div>

        <!-- CTA Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="${ticketUrl}" 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 Ticket
          </a>
        </div>

        <p style="margin: 20px 0 0; color: #6b7280; font-size: 14px; line-height: 1.6;">
          If you need further assistance, you can reply to this ticket from your dashboard.
        </p>
      </div>

      <!-- Footer -->
      <div style="padding: 20px 30px; background: #f9fafb; text-align: center;">
        <p style="margin: 0; color: #9ca3af; font-size: 12px;">
          Mawidi Support Team
        </p>
      </div>
    </div>
  </div>
</body>
</html>
`;

  const text = isAr
    ? `مرحباً ${data.recipientName}،\n\nتم الرد على تذكرتك "${data.ticketSubject}" من قبل ${data.senderName}.\n\nالرد:\n${data.messagePreview}\n\nلعرض التذكرة، قم بزيارة: ${ticketUrl}\n\nفريق دعم Mawidi`
    : `Hello ${data.recipientName},\n\nYour ticket "${data.ticketSubject}" has received a reply from ${data.senderName}.\n\nReply:\n${data.messagePreview}\n\nTo view the ticket, visit: ${ticketUrl}\n\nMawidi Support Team`;

  return { subject, html, text };
}

/**
 * Generate status change notification email template
 */
function generateStatusChangeEmail(data: StatusChangeEmailData) {
  const isAr = data.lang === 'ar';
  const ticketUrl = `${BASE_URL}/${data.lang}/dashboard?tab=support`;

  const statusLabels: Record<string, { en: string; ar: string }> = {
    OPEN: { en: 'Open', ar: 'مفتوحة' },
    IN_PROGRESS: { en: 'In Progress', ar: 'قيد التنفيذ' },
    RESOLVED: { en: 'Resolved', ar: 'تم الحل' },
    CLOSED: { en: 'Closed', ar: 'مغلقة' },
  };

  const newStatusLabel = statusLabels[data.newStatus]?.[isAr ? 'ar' : 'en'] || data.newStatus;

  const subject = isAr
    ? `تحديث حالة التذكرة #${data.ticketId.slice(0, 8)}`
    : `Ticket Status Update #${data.ticketId.slice(0, 8)}`;

  const statusColor = {
    OPEN: '#3b82f6',
    IN_PROGRESS: '#f59e0b',
    RESOLVED: '#10b981',
    CLOSED: '#6b7280',
  }[data.newStatus] || '#6b7280';

  const html = isAr
    ? `
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<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; direction: rtl;">
  <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, ${statusColor} 0%, ${statusColor}dd 100%); padding: 30px; text-align: center;">
        <h1 style="margin: 0; color: white; font-size: 24px; font-weight: 600;">تحديث حالة التذكرة</h1>
      </div>

      <!-- Content -->
      <div style="padding: 30px;">
        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          مرحباً ${data.recipientName}،
        </p>

        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          تم تحديث حالة تذكرتك "<strong>${data.ticketSubject}</strong>" إلى:
        </p>

        <!-- Status Badge -->
        <div style="text-align: center; margin: 30px 0;">
          <span style="display: inline-block; background: ${statusColor}20; color: ${statusColor}; padding: 12px 24px; border-radius: 50px; font-weight: 600; font-size: 18px;">
            ${newStatusLabel}
          </span>
        </div>

        <!-- CTA Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="${ticketUrl}" 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;">
            عرض التذكرة
          </a>
        </div>
      </div>

      <!-- Footer -->
      <div style="padding: 20px 30px; background: #f9fafb; text-align: center;">
        <p style="margin: 0; color: #9ca3af; font-size: 12px;">
          فريق دعم Mawidi
        </p>
      </div>
    </div>
  </div>
</body>
</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, ${statusColor} 0%, ${statusColor}dd 100%); padding: 30px; text-align: center;">
        <h1 style="margin: 0; color: white; font-size: 24px; font-weight: 600;">Ticket Status Update</h1>
      </div>

      <!-- Content -->
      <div style="padding: 30px;">
        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          Hello ${data.recipientName},
        </p>

        <p style="margin: 0 0 20px; color: #374151; font-size: 16px; line-height: 1.6;">
          Your ticket "<strong>${data.ticketSubject}</strong>" status has been updated to:
        </p>

        <!-- Status Badge -->
        <div style="text-align: center; margin: 30px 0;">
          <span style="display: inline-block; background: ${statusColor}20; color: ${statusColor}; padding: 12px 24px; border-radius: 50px; font-weight: 600; font-size: 18px;">
            ${newStatusLabel}
          </span>
        </div>

        <!-- CTA Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="${ticketUrl}" 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 Ticket
          </a>
        </div>
      </div>

      <!-- Footer -->
      <div style="padding: 20px 30px; background: #f9fafb; text-align: center;">
        <p style="margin: 0; color: #9ca3af; font-size: 12px;">
          Mawidi Support Team
        </p>
      </div>
    </div>
  </div>
</body>
</html>
`;

  const text = isAr
    ? `مرحباً ${data.recipientName}،\n\nتم تحديث حالة تذكرتك "${data.ticketSubject}" إلى: ${newStatusLabel}\n\nلعرض التذكرة، قم بزيارة: ${ticketUrl}\n\nفريق دعم Mawidi`
    : `Hello ${data.recipientName},\n\nYour ticket "${data.ticketSubject}" status has been updated to: ${newStatusLabel}\n\nTo view the ticket, visit: ${ticketUrl}\n\nMawidi Support Team`;

  return { subject, html, text };
}
