import { invokeLLM } from "../_core/llm.ts";

export interface EmailTemplate {
  to: string;
  subject: string;
  template: string;
  data: Record<string, any>;
}

export interface EmailNotification {
  userId: string;
  type: 'win' | 'bonus' | 'promotion' | 'achievement' | 'referral' | 'withdrawal' | 'kyc_update';
  title: string;
  message: string;
  data?: Record<string, any>;
}

const EMAIL_TEMPLATES = {
  big_win: (data: any) => `
    <h2>🎉 Big Win!</h2>
    <p>Congratulations! You just won <strong>${data.amount} SC</strong> on ${data.gameName}!</p>
    <p>Your new balance: <strong>${data.newBalance} SC</strong></p>
    <p><a href="${data.gameUrl}">Play again</a></p>
  `,
  
  daily_bonus: (data: any) => `
    <h2>💰 Daily Bonus Claimed</h2>
    <p>You've claimed your daily bonus of <strong>${data.amount} SC</strong>!</p>
    <p>Come back tomorrow for more rewards.</p>
    <p><a href="${data.casinoUrl}">Play now</a></p>
  `,
  
  achievement_unlocked: (data: any) => `
    <h2>🏆 Achievement Unlocked!</h2>
    <p>You've unlocked the <strong>${data.achievementName}</strong> achievement!</p>
    <p>Reward: <strong>${data.reward} points</strong></p>
    <p><a href="${data.achievementsUrl}">View all achievements</a></p>
  `,
  
  referral_bonus: (data: any) => `
    <h2>👥 Referral Bonus</h2>
    <p><strong>${data.referredUsername}</strong> joined using your referral code!</p>
    <p>You've earned <strong>${data.bonusAmount} SC</strong>!</p>
    <p>Your referral code: <strong>${data.referralCode}</strong></p>
    <p><a href="${data.referralUrl}">Share more</a></p>
  `,
  
  withdrawal_pending: (data: any) => `
    <h2>💸 Withdrawal Pending</h2>
    <p>Your withdrawal request of <strong>${data.amount}</strong> is being processed.</p>
    <p>Method: ${data.method}</p>
    <p>Expected time: ${data.estimatedTime}</p>
    <p><a href="${data.walletUrl}">Track status</a></p>
  `,
  
  kyc_approved: (data: any) => `
    <h2>✅ KYC Approved</h2>
    <p>Your identity verification has been approved!</p>
    <p>You can now withdraw funds and access all features.</p>
    <p><a href="${data.walletUrl}">Go to wallet</a></p>
  `,
  
  promotion: (data: any) => `
    <h2>🎁 Special Promotion</h2>
    <p>${data.promotionTitle}</p>
    <p>${data.promotionDescription}</p>
    <p><strong>Offer expires: ${data.expiryDate}</strong></p>
    <p><a href="${data.promotionUrl}">Claim offer</a></p>
  `,
};

export async function sendEmailNotification(notification: EmailNotification, userEmail: string): Promise<boolean> {
  try {
    const template = EMAIL_TEMPLATES[notification.type as keyof typeof EMAIL_TEMPLATES];
    
    if (!template) {
      console.warn(`Unknown email template: ${notification.type}`);
      return false;
    }

    const htmlContent = template(notification.data || {});

    // Use the built-in notification system to send email
    const response = await fetch(`${process.env.BUILT_IN_FORGE_API_URL}/notification/send-email`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.BUILT_IN_FORGE_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: userEmail,
        subject: notification.title,
        htmlContent,
        textContent: notification.message,
      }),
    });

    return response.ok;
  } catch (error) {
    console.error('Failed to send email notification:', error);
    return false;
  }
}

export async function sendBulkEmailNotifications(
  notifications: Array<{ userId: string; email: string; notification: EmailNotification }>
): Promise<Map<string, boolean>> {
  const results = new Map<string, boolean>();

  for (const { userId, email, notification } of notifications) {
    const success = await sendEmailNotification(notification, email);
    results.set(userId, success);
  }

  return results;
}

export async function sendPromotionalEmail(
  userEmail: string,
  title: string,
  content: string,
  ctaUrl: string,
  ctaText: string = 'View Offer'
): Promise<boolean> {
  try {
    const htmlContent = `
      <h2>${title}</h2>
      <p>${content}</p>
      <p><a href="${ctaUrl}" style="background-color: #3b82f6; color: #000; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">${ctaText}</a></p>
    `;

    const response = await fetch(`${process.env.BUILT_IN_FORGE_API_URL}/notification/send-email`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.BUILT_IN_FORGE_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: userEmail,
        subject: title,
        htmlContent,
        textContent: content,
      }),
    });

    return response.ok;
  } catch (error) {
    console.error('Failed to send promotional email:', error);
    return false;
  }
}

export async function sendTransactionalEmail(
  userEmail: string,
  subject: string,
  htmlContent: string,
  textContent: string
): Promise<boolean> {
  try {
    const response = await fetch(`${process.env.BUILT_IN_FORGE_API_URL}/notification/send-email`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.BUILT_IN_FORGE_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: userEmail,
        subject,
        htmlContent,
        textContent,
      }),
    });

    return response.ok;
  } catch (error) {
    console.error('Failed to send transactional email:', error);
    return false;
  }
}


/**
 * Send magic link email for passwordless authentication
 */
export async function sendMagicLinkEmail(
  userEmail: string,
  magicLink: string,
  expiresInMinutes: number = 15
): Promise<boolean> {
  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Sign in to CoinKrazy</h2>
      <p>Click the button below to sign in without a password:</p>
      <div style="margin: 30px 0;">
        <a href="${magicLink}" style="background-color: #2563eb; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; display: inline-block; font-weight: bold;">
          Sign in to CoinKrazy
        </a>
      </div>
      <p style="color: #666;">Or copy and paste this link in your browser:</p>
      <p style="background-color: #f3f4f6; padding: 10px; border-radius: 4px; word-break: break-all;">
        ${magicLink}
      </p>
      <p style="color: #999; font-size: 12px;">
        This link expires in ${expiresInMinutes} minutes.
      </p>
      <p style="color: #999; font-size: 12px;">
        If you didn't request this link, you can safely ignore this email.
      </p>
      <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 30px 0;">
      <p style="color: #999; font-size: 12px; text-align: center;">
        © 2026 CoinKrazy. All rights reserved.
      </p>
    </div>
  `;

  const textContent = `
    Sign in to CoinKrazy

    Click the link below to sign in without a password:
    ${magicLink}

    This link expires in ${expiresInMinutes} minutes.

    If you didn't request this link, you can safely ignore this email.
  `;

  return sendTransactionalEmail(userEmail, 'Sign in to CoinKrazy', htmlContent, textContent);
}

/**
 * Send 2FA setup email
 */
export async function send2FASetupEmail(
  userEmail: string,
  qrCodeUrl: string,
  secret: string
): Promise<boolean> {
  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Set Up Two-Factor Authentication</h2>
      <p>We're helping you secure your CoinKrazy account with two-factor authentication.</p>
      
      <h3>Step 1: Scan QR Code</h3>
      <p>Use an authenticator app (Google Authenticator, Authy, Microsoft Authenticator) to scan this QR code:</p>
      <div style="text-align: center; margin: 20px 0;">
        <img src="${qrCodeUrl}" alt="QR Code" style="width: 200px; height: 200px;">
      </div>
      
      <h3>Step 2: Manual Entry (if needed)</h3>
      <p>If you can't scan the QR code, enter this secret key manually:</p>
      <p style="background-color: #f3f4f6; padding: 10px; border-radius: 4px; font-family: monospace; word-break: break-all;">
        ${secret}
      </p>
      
      <p style="color: #999; font-size: 12px;">
        Keep this secret key in a safe place. You'll need it to recover your account if you lose access to your authenticator app.
      </p>
    </div>
  `;

  return sendTransactionalEmail(userEmail, 'Set Up Two-Factor Authentication for CoinKrazy', htmlContent, '');
}

/**
 * Send welcome email
 */
export async function sendWelcomeEmail(
  userEmail: string,
  name: string
): Promise<boolean> {
  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Welcome to CoinKrazy, ${name}!</h2>
      <p>Your account has been created successfully.</p>
      
      <h3>Get Started:</h3>
      <ul>
        <li>Complete your profile</li>
        <li>Claim your welcome bonus</li>
        <li>Play 700+ games</li>
        <li>Win real prizes</li>
      </ul>
      
      <p>
        <a href="https://playcoinkrazy.com/dashboard" style="background-color: #2563eb; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; display: inline-block; font-weight: bold;">
          Go to Dashboard
        </a>
      </p>
    </div>
  `;

  return sendTransactionalEmail(userEmail, 'Welcome to CoinKrazy!', htmlContent, '');
}


/**
 * Send email verification link
 */
export async function sendEmailVerificationLink(
  userEmail: string,
  token: string
): Promise<boolean> {
  const verificationUrl = `${process.env.FRONTEND_URL || "https://playplaycoinkrazy.com"}/verify-email?token=${token}`;

  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Verify Your Email Address</h2>
      <p>Thank you for joining CoinKrazy! To complete your email verification, click the button below:</p>
      <div style="margin: 30px 0;">
        <a href="${verificationUrl}" style="background-color: #2563eb; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; display: inline-block; font-weight: bold;">
          Verify Email Address
        </a>
      </div>
      <p style="color: #666;">Or copy and paste this link in your browser:</p>
      <p style="background-color: #f3f4f6; padding: 10px; border-radius: 4px; word-break: break-all; font-size: 12px;">
        ${verificationUrl}
      </p>
      <p style="color: #999; font-size: 12px;">
        This link will expire in 24 hours.
      </p>
      <p style="color: #999; font-size: 12px;">
        If you didn't request this email, you can safely ignore it.
      </p>
      <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 30px 0;">
      <p style="color: #999; font-size: 12px; text-align: center;">
        © 2026 CoinKrazy. All rights reserved.
      </p>
    </div>
  `;

  const textContent = `
    Verify Your Email Address

    Thank you for joining CoinKrazy! To complete your email verification, click the link below:
    ${verificationUrl}

    This link will expire in 24 hours.

    If you didn't request this email, you can safely ignore it.
  `;

  return sendTransactionalEmail(userEmail, 'Verify Your CoinKrazy Email Address', htmlContent, textContent);
}


/**
 * Send scheduled export email with attachments
 */
export async function sendScheduledExportEmail(
  recipients: string[],
  reportTitle: string,
  reportData: string,
  attachments?: Array<{ filename: string; content: Buffer | string; contentType?: string }>
): Promise<boolean> {
  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Scheduled Report: ${reportTitle}</h2>
      <p>Your scheduled export has been generated and is ready for download.</p>
      <div style="background-color: #f3f4f6; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
        <p style="margin: 0; color: #333;">
          <strong>Report:</strong> ${reportTitle}<br>
          <strong>Generated:</strong> ${new Date().toLocaleString()}<br>
          <strong>Format:</strong> CSV/PDF
        </p>
      </div>
      <p style="color: #666; font-size: 12px;">
        This is an automated email from CoinKrazy Admin System. Please do not reply to this email.
      </p>
    </div>
  `;

  const textContent = `
    Scheduled Report: ${reportTitle}

    Your scheduled export has been generated and is ready for download.

    Report: ${reportTitle}
    Generated: ${new Date().toLocaleString()}
    Format: CSV/PDF

    This is an automated email from CoinKrazy Admin System.
  `;

  // Send to all recipients
  for (const recipient of recipients) {
    const success = await sendTransactionalEmail(
      recipient,
      `CoinKrazy Report: ${reportTitle}`,
      htmlContent,
      textContent
    );
    if (!success) {
      console.warn(`Failed to send scheduled export email to ${recipient}`);
    }
  }

  return true;
}

/**
 * Send deployment notification email
 */
export async function sendDeploymentNotification(
  recipients: string[],
  gameName: string,
  deploymentStatus: 'success' | 'failed' | 'pending'
): Promise<boolean> {
  const statusColor = {
    success: '#10B981',
    failed: '#EF4444',
    pending: '#F59E0B'
  }[deploymentStatus];

  const statusText = {
    success: 'Successfully Deployed',
    failed: 'Deployment Failed',
    pending: 'Deployment Pending'
  }[deploymentStatus];

  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Game Deployment Notification</h2>
      <div style="background-color: ${statusColor}; color: white; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
        <p style="margin: 0; font-weight: bold; font-size: 16px;">${statusText}</p>
      </div>
      <p style="color: #666; margin-bottom: 10px;">
        <strong>Game:</strong> ${gameName}<br>
        <strong>Timestamp:</strong> ${new Date().toLocaleString()}
      </p>
      <p style="color: #666; font-size: 12px;">
        This is an automated notification from CoinKrazy Admin System.
      </p>
    </div>
  `;

  const textContent = `
    Game Deployment Notification

    ${statusText}

    Game: ${gameName}
    Timestamp: ${new Date().toLocaleString()}

    This is an automated notification from CoinKrazy Admin System.
  `;

  // Send to all recipients
  for (const recipient of recipients) {
    await sendTransactionalEmail(
      recipient,
      `Game Deployment: ${gameName} - ${statusText}`,
      htmlContent,
      textContent
    );
  }

  return true;
}

/**
 * Send test email to verify email service configuration
 */
export async function sendTestEmail(recipient: string): Promise<boolean> {
  const htmlContent = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #2563eb;">Test Email</h2>
      <p>This is a test email from CoinKrazy Admin System. If you received this, email notifications are working correctly.</p>
      <p style="color: #666; font-size: 12px; margin-top: 20px;">
        Sent at: ${new Date().toLocaleString()}
      </p>
    </div>
  `;

  const textContent = `
    Test Email

    This is a test email from CoinKrazy Admin System. If you received this, email notifications are working correctly.

    Sent at: ${new Date().toLocaleString()}
  `;

  return sendTransactionalEmail(recipient, 'CoinKrazy Test Email', htmlContent, textContent);
}
