/**
 * Team Invitation Emails Service
 *
 * Business logic layer for team invitation email operations.
 * Handles sending invitation emails with proper error handling and logging.
 *
 * @module services/team-invitation-emails
 */

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

/**
 * Email template interface
 */
interface EmailTemplate {
  subject: string;
  html: string;
  text: string;
}

/**
 * Send team invitation email
 *
 * Sends a professional invitation email with a unique token link.
 * Supports both Arabic and English languages.
 *
 * @param email - Invitee email address
 * @param inviteeName - Invitee name (optional)
 * @param orgName - Organization name
 * @param inviterName - Name of person sending invitation
 * @param role - Role being offered (ADMIN or STAFF)
 * @param token - Unique invitation token
 * @param expiresAt - Expiration date
 * @param lang - Language preference (ar or en)
 * @returns Success status and optional error message
 *
 * @example
 * const result = await sendTeamInvitation(
 *   'staff@example.com',
 *   'John Doe',
 *   'Acme Clinic',
 *   'Jane Smith',
 *   'STAFF',
 *   'abc123xyz',
 *   new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
 *   'en'
 * );
 */
export async function sendTeamInvitation(params: {
  email: string;
  inviteeName?: string;
  orgName: string;
  inviterName: string;
  role: 'ADMIN' | 'STAFF';
  token: string;
  expiresAt: Date;
  lang: 'ar' | 'en';
}): Promise<{ success: boolean; error?: string }> {
  try {
    const {
      email,
      inviteeName,
      orgName,
      inviterName,
      role,
      token,
      expiresAt,
      lang,
    } = params;

    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:9000';
    const inviteLink = `${baseUrl}/${lang}/invite/${token}`;

    const isArabic = lang === 'ar';

    // Format expiry date
    const expiryDate = expiresAt.toLocaleDateString(
      isArabic ? 'ar-SA' : 'en-US',
      { year: 'numeric', month: 'long', day: 'numeric' }
    );

    // Role translation
    const roleText = isArabic
      ? role === 'ADMIN'
        ? 'مسؤول'
        : 'موظف'
      : role === 'ADMIN'
      ? 'Admin'
      : 'Staff Member';

    // Create email template
    const template = createTeamInvitationEmail({
      inviteeName,
      orgName,
      inviterName,
      role: roleText,
      inviteLink,
      expiryDate,
      lang,
    });

    const sent = await sendEmail(email, template);

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

    logger.info('[Team Invitation] Email sent', { email, orgName, role });
    return { success: true };
  } catch (error) {
    logger.error('[Team Invitation] Failed to send email', error);
    return { success: false, error: 'Internal error sending email' };
  }
}

/**
 * Create team invitation email template
 *
 * @private
 */
function createTeamInvitationEmail(params: {
  inviteeName?: string;
  orgName: string;
  inviterName: string;
  role: string;
  inviteLink: string;
  expiryDate: string;
  lang: 'ar' | 'en';
}): EmailTemplate {
  const { inviteeName, orgName, inviterName, role, inviteLink, expiryDate, lang } = params;
  const isArabic = lang === 'ar';

  const greeting = inviteeName
    ? isArabic
      ? `مرحباً ${inviteeName}،`
      : `Hello ${inviteeName},`
    : isArabic
    ? 'مرحباً،'
    : 'Hello,';

  const subject = isArabic
    ? `دعوة للانضمام إلى فريق ${orgName} على Mawidi`
    : `You're invited to join ${orgName} on Mawidi`;

  if (isArabic) {
    const html = `
      <!DOCTYPE html>
      <html dir="rtl" lang="ar">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
          body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
            line-height: 1.6;
            color: #1f2937;
            background-color: #f9fafb;
            margin: 0;
            padding: 0;
          }
          .container {
            max-width: 600px;
            margin: 40px auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
          }
          .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
          }
          .header h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
          }
          .content {
            padding: 40px 30px;
          }
          .greeting {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #111827;
          }
          .message {
            font-size: 16px;
            line-height: 1.8;
            color: #374151;
            margin-bottom: 20px;
          }
          .role-badge {
            display: inline-block;
            background: #ede9fe;
            color: #5b21b6;
            padding: 6px 16px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 14px;
            margin: 10px 0;
          }
          .cta-button {
            display: inline-block;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 16px 32px;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 16px;
            margin: 30px 0;
            text-align: center;
            transition: transform 0.2s;
          }
          .cta-button:hover {
            transform: translateY(-2px);
          }
          .expiry-notice {
            background: #fef3c7;
            border-right: 4px solid #f59e0b;
            padding: 16px;
            margin: 20px 0;
            border-radius: 6px;
            font-size: 14px;
            color: #78350f;
          }
          .footer {
            background: #f3f4f6;
            padding: 30px;
            text-align: center;
            font-size: 14px;
            color: #6b7280;
          }
          .link-fallback {
            background: #f9fafb;
            padding: 12px;
            border: 1px dashed #d1d5db;
            border-radius: 6px;
            font-size: 12px;
            color: #6b7280;
            margin-top: 20px;
            word-break: break-all;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>🎉 دعوة انضمام للفريق</h1>
          </div>

          <div class="content">
            <p class="greeting">${greeting}</p>

            <p class="message">
              تمت دعوتك للانضمام إلى <strong>${orgName}</strong> من قبل
              <strong>${inviterName}</strong> على منصة Mawidi.
            </p>

            <p class="message">
              ستنضم بصفة:
              <span class="role-badge">${role}</span>
            </p>

            <p class="message">
              انقر على الزر أدناه لقبول الدعوة وإعداد حسابك:
            </p>

            <div style="text-align: center;">
              <a href="${inviteLink}" class="cta-button">
                قبول الدعوة وإنشاء حساب
              </a>
            </div>

            <div class="expiry-notice">
              <strong>⏰ تنتهي صلاحية الدعوة في:</strong> ${expiryDate}
            </div>

            <p class="message">
              بعد قبول الدعوة، ستتمكن من الوصول إلى لوحة التحكم والبدء في العمل مع فريقك.
            </p>

            <div class="link-fallback">
              <strong>الرابط لا يعمل؟</strong> انسخ والصق هذا العنوان في متصفحك:<br>
              ${inviteLink}
            </div>
          </div>

          <div class="footer">
            <p>هذه رسالة تلقائية من Mawidi</p>
            <p>إذا لم تتوقع هذه الدعوة، يمكنك تجاهل هذه الرسالة بأمان</p>
            <p style="margin-top: 20px;">
              <a href="https://mawidi.com" style="color: #667eea; text-decoration: none;">mawidi.com</a>
            </p>
          </div>
        </div>
      </body>
      </html>
    `;

    const text = `
${greeting}

تمت دعوتك للانضمام إلى ${orgName} من قبل ${inviterName} على منصة Mawidi.

الدور: ${role}

لقبول الدعوة، انقر على الرابط التالي:
${inviteLink}

تنتهي صلاحية الدعوة في: ${expiryDate}

إذا لم تتوقع هذه الدعوة، يمكنك تجاهل هذه الرسالة بأمان.

---
Mawidi
    `.trim();

    return { subject, html, text };
  }

  // English template
  const html = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
          line-height: 1.6;
          color: #1f2937;
          background-color: #f9fafb;
          margin: 0;
          padding: 0;
        }
        .container {
          max-width: 600px;
          margin: 40px auto;
          background: white;
          border-radius: 12px;
          box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
          overflow: hidden;
        }
        .header {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          padding: 40px 30px;
          text-align: center;
          color: white;
        }
        .header h1 {
          margin: 0;
          font-size: 28px;
          font-weight: 700;
        }
        .content {
          padding: 40px 30px;
        }
        .greeting {
          font-size: 18px;
          font-weight: 600;
          margin-bottom: 20px;
          color: #111827;
        }
        .message {
          font-size: 16px;
          line-height: 1.8;
          color: #374151;
          margin-bottom: 20px;
        }
        .role-badge {
          display: inline-block;
          background: #ede9fe;
          color: #5b21b6;
          padding: 6px 16px;
          border-radius: 20px;
          font-weight: 600;
          font-size: 14px;
          margin: 10px 0;
        }
        .cta-button {
          display: inline-block;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          padding: 16px 32px;
          text-decoration: none;
          border-radius: 8px;
          font-weight: 600;
          font-size: 16px;
          margin: 30px 0;
          text-align: center;
          transition: transform 0.2s;
        }
        .cta-button:hover {
          transform: translateY(-2px);
        }
        .expiry-notice {
          background: #fef3c7;
          border-left: 4px solid #f59e0b;
          padding: 16px;
          margin: 20px 0;
          border-radius: 6px;
          font-size: 14px;
          color: #78350f;
        }
        .footer {
          background: #f3f4f6;
          padding: 30px;
          text-align: center;
          font-size: 14px;
          color: #6b7280;
        }
        .link-fallback {
          background: #f9fafb;
          padding: 12px;
          border: 1px dashed #d1d5db;
          border-radius: 6px;
          font-size: 12px;
          color: #6b7280;
          margin-top: 20px;
          word-break: break-all;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="header">
          <h1>🎉 Team Invitation</h1>
        </div>

        <div class="content">
          <p class="greeting">${greeting}</p>

          <p class="message">
            You have been invited to join <strong>${orgName}</strong> by
            <strong>${inviterName}</strong> on Mawidi.
          </p>

          <p class="message">
            You'll be joining as:
            <span class="role-badge">${role}</span>
          </p>

          <p class="message">
            Click the button below to accept the invitation and set up your account:
          </p>

          <div style="text-align: center;">
            <a href="${inviteLink}" class="cta-button">
              Accept Invitation & Create Account
            </a>
          </div>

          <div class="expiry-notice">
            <strong>⏰ This invitation expires on:</strong> ${expiryDate}
          </div>

          <p class="message">
            Once you accept, you'll have access to the dashboard and can start working with your team.
          </p>

          <div class="link-fallback">
            <strong>Link not working?</strong> Copy and paste this URL into your browser:<br>
            ${inviteLink}
          </div>
        </div>

        <div class="footer">
          <p>This is an automated message from Mawidi</p>
          <p>If you weren't expecting this invitation, you can safely ignore this email</p>
          <p style="margin-top: 20px;">
            <a href="https://mawidi.com" style="color: #667eea; text-decoration: none;">mawidi.com</a>
          </p>
        </div>
      </div>
    </body>
    </html>
  `;

  const text = `
${greeting}

You have been invited to join ${orgName} by ${inviterName} on Mawidi.

Role: ${role}

To accept the invitation, click the link below:
${inviteLink}

This invitation expires on: ${expiryDate}

If you weren't expecting this invitation, you can safely ignore this email.

---
Mawidi
  `.trim();

  return { subject, html, text };
}

/**
 * Example usage:
 *
 * ```typescript
 * import * as teamInvitationEmails from '@/lib/services/team-invitation-emails.service';
 *
 * const result = await teamInvitationEmails.sendTeamInvitation({
 *   email: 'staff@example.com',
 *   inviteeName: 'John Doe',
 *   orgName: 'Acme Medical Clinic',
 *   inviterName: 'Dr. Jane Smith',
 *   role: 'STAFF',
 *   token: 'abc123xyz789',
 *   expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
 *   lang: 'en'
 * });
 *
 * if (result.success) {
 *   console.log('Invitation email sent successfully');
 * } else {
 *   console.error('Failed to send invitation:', result.error);
 * }
 * ```
 */
