import { Resend } from 'resend';
import QRCode from 'qrcode';
import { logUserActivity } from './logger';

// Initialize Resend
const resend = new Resend(process.env.RESEND_API_KEY);

// Email configuration
export const EMAIL_CONFIG = {
  FROM_EMAIL: 'Black Canyon Tickets <tickets@blackcanyontickets.com>',
  FROM_NAME: 'Black Canyon Tickets',
  SUPPORT_EMAIL: 'support@blackcanyontickets.com',
  DOMAIN: process.env.PUBLIC_APP_URL || 'https://portal.blackcanyontickets.com'
};

// Validate email configuration
if (!process.env.RESEND_API_KEY) {
  console.warn('RESEND_API_KEY environment variable is not set. Email functionality will be disabled.');
}

export interface TicketEmailData {
  ticketId: string;
  ticketUuid: string;
  eventTitle: string;
  eventVenue: string;
  eventDate: string;
  eventTime: string;
  ticketType: string;
  seatInfo?: string;
  price: number;
  purchaserName: string;
  purchaserEmail: string;
  organizerName: string;
  organizerEmail: string;
  qrCodeUrl: string;
  orderNumber: string;
  totalAmount: number;
  platformFee: number;
  eventDescription?: string;
  eventAddress?: string;
  additionalInfo?: string;
}

export interface OrderConfirmationData {
  orderNumber: string;
  purchaserName: string;
  purchaserEmail: string;
  eventTitle: string;
  eventVenue: string;
  eventDate: string;
  totalAmount: number;
  platformFee: number;
  tickets: Array<{
    type: string;
    quantity: number;
    price: number;
    seatInfo?: string;
  }>;
  organizerName: string;
  refundPolicy?: string;
}

/**
 * Generate QR code data URL for email
 */
async function generateQRCodeDataURL(ticketUuid: string): Promise<string> {
  try {
    const qrData = `${EMAIL_CONFIG.DOMAIN}/verify/${ticketUuid}`;
    const qrCodeDataURL = await QRCode.toDataURL(qrData, {
      errorCorrectionLevel: 'M',
      type: 'image/png',
      quality: 0.92,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      },
      width: 200
    });
    return qrCodeDataURL;
  } catch (error) {
    console.error('Error generating QR code:', error);
    throw error;
  }
}

/**
 * Create ticket confirmation email HTML
 */
function createTicketEmailHTML(data: TicketEmailData): string {
  return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Ticket for ${data.eventTitle}</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8fafc;
        }
        .container {
            background-color: #ffffff;
            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%);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .content {
            padding: 30px 20px;
        }
        .ticket-section {
            background-color: #f1f5f9;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
            border-left: 4px solid #3b82f6;
        }
        .qr-section {
            text-align: center;
            background-color: #ffffff;
            border: 2px dashed #d1d5db;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        .event-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin: 20px 0;
        }
        .detail-item {
            background-color: #f8fafc;
            padding: 12px;
            border-radius: 6px;
        }
        .detail-label {
            font-weight: 600;
            color: #64748b;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }
        .detail-value {
            color: #1e293b;
            font-size: 14px;
            font-weight: 500;
        }
        .footer {
            background-color: #f1f5f9;
            padding: 20px;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }
        .button {
            display: inline-block;
            background-color: #3b82f6;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            margin: 10px 0;
        }
        .important-note {
            background-color: #fef3c7;
            border: 1px solid #f59e0b;
            border-radius: 6px;
            padding: 15px;
            margin: 20px 0;
        }
        @media (max-width: 600px) {
            .event-details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 style="margin: 0; font-size: 24px;">🎫 Your Ticket is Ready!</h1>
            <p style="margin: 10px 0 0; opacity: 0.9;">You're all set for ${data.eventTitle}</p>
        </div>
        
        <div class="content">
            <p>Hi ${data.purchaserName},</p>
            
            <p>Thanks for your purchase! Your ticket for <strong>${data.eventTitle}</strong> is confirmed and ready to use.</p>
            
            <div class="ticket-section">
                <h2 style="margin-top: 0; color: #1e293b; font-size: 18px;">📍 Event Details</h2>
                <div class="event-details">
                    <div class="detail-item">
                        <div class="detail-label">Event</div>
                        <div class="detail-value">${data.eventTitle}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Date & Time</div>
                        <div class="detail-value">${data.eventDate} at ${data.eventTime}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Venue</div>
                        <div class="detail-value">${data.eventVenue}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Ticket Type</div>
                        <div class="detail-value">${data.ticketType}${data.seatInfo ? ` - ${data.seatInfo}` : ''}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Order Number</div>
                        <div class="detail-value">${data.orderNumber}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">Amount Paid</div>
                        <div class="detail-value">$${(data.totalAmount / 100).toFixed(2)}</div>
                    </div>
                </div>
            </div>
            
            <div class="qr-section">
                <h3 style="color: #1e293b; margin-top: 0;">📱 Your Digital Ticket</h3>
                <p style="color: #64748b; margin-bottom: 20px;">Present this QR code at the venue for entry</p>
                <img src="${data.qrCodeUrl}" alt="Ticket QR Code" style="max-width: 200px; height: auto;" />
                <p style="font-size: 12px; color: #64748b; margin-top: 15px;">
                    Ticket ID: ${data.ticketUuid}
                </p>
            </div>
            
            <div class="important-note">
                <strong>📋 Important Information:</strong>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    <li>Save this email or screenshot the QR code</li>
                    <li>Arrive 15-30 minutes early for entry</li>
                    <li>Present a valid ID if required</li>
                    <li>This ticket is non-transferable unless specified</li>
                </ul>
            </div>
            
            ${data.additionalInfo ? `
            <div style="background-color: #e0f2fe; border-radius: 6px; padding: 15px; margin: 20px 0;">
                <strong>Additional Information:</strong>
                <p style="margin: 10px 0 0;">${data.additionalInfo}</p>
            </div>
            ` : ''}
            
            <div style="text-align: center; margin: 30px 0;">
                <a href="${EMAIL_CONFIG.DOMAIN}/e/${data.eventTitle.toLowerCase().replace(/\s+/g, '-')}" class="button">
                    View Event Details
                </a>
            </div>
            
            <p>Questions? Contact the event organizer at <a href="mailto:${data.organizerEmail}">${data.organizerEmail}</a> or our support team at <a href="mailto:${EMAIL_CONFIG.SUPPORT_EMAIL}">${EMAIL_CONFIG.SUPPORT_EMAIL}</a>.</p>
            
            <p>We hope you have a great time at the event!</p>
            
            <p style="color: #64748b; font-size: 14px;">
                Best regards,<br>
                The Black Canyon Tickets Team
            </p>
        </div>
        
        <div class="footer">
            <p style="margin: 0; font-size: 12px; color: #64748b;">
                This email was sent by Black Canyon Tickets.<br>
                <a href="${EMAIL_CONFIG.DOMAIN}/privacy" style="color: #3b82f6;">Privacy Policy</a> | 
                <a href="${EMAIL_CONFIG.DOMAIN}/terms" style="color: #3b82f6;">Terms of Service</a>
            </p>
        </div>
    </div>
</body>
</html>`;
}

/**
 * Create order confirmation email HTML
 */
function createOrderConfirmationHTML(data: OrderConfirmationData): string {
  const ticketList = data.tickets.map(ticket => 
    `<li>${ticket.quantity}x ${ticket.type}${ticket.seatInfo ? ` (${ticket.seatInfo})` : ''} - $${(ticket.price / 100).toFixed(2)} each</li>`
  ).join('');

  return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Confirmation - ${data.eventTitle}</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8fafc;
        }
        .container {
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .content {
            padding: 30px 20px;
        }
        .order-summary {
            background-color: #f1f5f9;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        .footer {
            background-color: #f1f5f9;
            padding: 20px;
            text-align: center;
            border-top: 1px solid #e2e8f0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 style="margin: 0; font-size: 24px;">✅ Order Confirmed!</h1>
            <p style="margin: 10px 0 0; opacity: 0.9;">Order #${data.orderNumber}</p>
        </div>
        
        <div class="content">
            <p>Hi ${data.purchaserName},</p>
            
            <p>Your order for <strong>${data.eventTitle}</strong> has been confirmed! You'll receive individual ticket emails shortly with QR codes for entry.</p>
            
            <div class="order-summary">
                <h3 style="margin-top: 0; color: #1e293b;">📋 Order Summary</h3>
                <p><strong>Event:</strong> ${data.eventTitle}<br>
                <strong>Venue:</strong> ${data.eventVenue}<br>
                <strong>Date:</strong> ${data.eventDate}</p>
                
                <h4 style="color: #1e293b;">Tickets Purchased:</h4>
                <ul>
                    ${ticketList}
                </ul>
                
                <hr style="border: none; border-top: 1px solid #e2e8f0; margin: 20px 0;">
                
                <div style="display: flex; justify-content: space-between; margin: 10px 0;">
                    <span>Subtotal:</span>
                    <span>$${((data.totalAmount - data.platformFee) / 100).toFixed(2)}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin: 10px 0;">
                    <span>Platform Fee:</span>
                    <span>$${(data.platformFee / 100).toFixed(2)}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin: 10px 0; font-weight: bold; font-size: 18px; border-top: 1px solid #e2e8f0; padding-top: 10px;">
                    <span>Total:</span>
                    <span>$${(data.totalAmount / 100).toFixed(2)}</span>
                </div>
            </div>
            
            <p>Your individual ticket emails with QR codes will arrive within the next few minutes. If you don't receive them, please check your spam folder.</p>
            
            ${data.refundPolicy ? `
            <div style="background-color: #fef3c7; border: 1px solid #f59e0b; border-radius: 6px; padding: 15px; margin: 20px 0;">
                <strong>Refund Policy:</strong>
                <p style="margin: 10px 0 0;">${data.refundPolicy}</p>
            </div>
            ` : ''}
            
            <p>Questions about your order? Contact ${data.organizerName} at <a href="mailto:${data.purchaserEmail}">${data.purchaserEmail}</a> or our support team at <a href="mailto:${EMAIL_CONFIG.SUPPORT_EMAIL}">${EMAIL_CONFIG.SUPPORT_EMAIL}</a>.</p>
            
            <p style="color: #64748b; font-size: 14px;">
                Best regards,<br>
                The Black Canyon Tickets Team
            </p>
        </div>
        
        <div class="footer">
            <p style="margin: 0; font-size: 12px; color: #64748b;">
                This email was sent by Black Canyon Tickets.<br>
                <a href="${EMAIL_CONFIG.DOMAIN}/privacy" style="color: #3b82f6;">Privacy Policy</a> | 
                <a href="${EMAIL_CONFIG.DOMAIN}/terms" style="color: #3b82f6;">Terms of Service</a>
            </p>
        </div>
    </div>
</body>
</html>`;
}

/**
 * Send ticket confirmation email
 */
export async function sendTicketConfirmationEmail(ticketData: TicketEmailData): Promise<void> {
  if (!process.env.RESEND_API_KEY) {
    console.warn('Email service not configured. Skipping ticket confirmation email.');
    return;
  }

  try {
    // Generate QR code
    const qrCodeDataURL = await generateQRCodeDataURL(ticketData.ticketUuid);
    const emailData = { ...ticketData, qrCodeUrl: qrCodeDataURL };

    const { data, error } = await resend.emails.send({
      from: EMAIL_CONFIG.FROM_EMAIL,
      to: [ticketData.purchaserEmail],
      subject: `Your ticket for ${ticketData.eventTitle}`,
      html: createTicketEmailHTML(emailData),
      attachments: [
        {
          filename: `ticket-${ticketData.ticketUuid}.png`,
          content: qrCodeDataURL.split(',')[1], // Remove data URL prefix
          contentType: 'image/png'
        }
      ]
    });

    if (error) {
      throw error;
    }

    // Log successful email send
    logUserActivity({
      action: 'ticket_email_sent',
      userId: '', // No user context for email
      details: {
        ticketId: ticketData.ticketId,
        recipientEmail: ticketData.purchaserEmail,
        eventTitle: ticketData.eventTitle,
        emailId: data?.id
      }
    });

    console.log('Ticket confirmation email sent successfully:', data?.id);
  } catch (error) {
    console.error('Error sending ticket confirmation email:', error);
    throw error;
  }
}

/**
 * Send order confirmation email
 */
export async function sendOrderConfirmationEmail(orderData: OrderConfirmationData): Promise<void> {
  if (!process.env.RESEND_API_KEY) {
    console.warn('Email service not configured. Skipping order confirmation email.');
    return;
  }

  try {
    const { data, error } = await resend.emails.send({
      from: EMAIL_CONFIG.FROM_EMAIL,
      to: [orderData.purchaserEmail],
      subject: `Order confirmed for ${orderData.eventTitle} - #${orderData.orderNumber}`,
      html: createOrderConfirmationHTML(orderData)
    });

    if (error) {
      throw error;
    }

    // Log successful email send
    logUserActivity({
      action: 'order_confirmation_email_sent',
      userId: '', // No user context for email
      details: {
        orderNumber: orderData.orderNumber,
        recipientEmail: orderData.purchaserEmail,
        eventTitle: orderData.eventTitle,
        totalAmount: orderData.totalAmount,
        emailId: data?.id
      }
    });

    console.log('Order confirmation email sent successfully:', data?.id);
  } catch (error) {
    console.error('Error sending order confirmation email:', error);
    throw error;
  }
}

/**
 * Send organizer notification email
 */
export async function sendOrganizerNotificationEmail(data: {
  organizerEmail: string;
  organizerName: string;
  eventTitle: string;
  purchaserName: string;
  purchaserEmail: string;
  ticketType: string;
  amount: number;
  orderNumber: string;
}): Promise<void> {
  if (!process.env.RESEND_API_KEY) {
    return;
  }

  try {
    const { data: emailData, error } = await resend.emails.send({
      from: EMAIL_CONFIG.FROM_EMAIL,
      to: [data.organizerEmail],
      subject: `New ticket sale for ${data.eventTitle}`,
      html: `
        <h2>New Ticket Sale</h2>
        <p>Hi ${data.organizerName},</p>
        <p>You have a new ticket sale for <strong>${data.eventTitle}</strong>!</p>
        <ul>
          <li><strong>Customer:</strong> ${data.purchaserName} (${data.purchaserEmail})</li>
          <li><strong>Ticket Type:</strong> ${data.ticketType}</li>
          <li><strong>Amount:</strong> $${(data.amount / 100).toFixed(2)}</li>
          <li><strong>Order:</strong> #${data.orderNumber}</li>
        </ul>
        <p>View your full sales report at <a href="${EMAIL_CONFIG.DOMAIN}/dashboard">your dashboard</a>.</p>
      `
    });

    if (error) {
      console.error('Error sending organizer notification:', error);
    }
  } catch (error) {
    console.error('Error sending organizer notification email:', error);
  }
}

/**
 * Test email configuration
 */
export async function testEmailConfiguration(): Promise<boolean> {
  if (!process.env.RESEND_API_KEY) {
    return false;
  }

  try {
    const { error } = await resend.emails.send({
      from: EMAIL_CONFIG.FROM_EMAIL,
      to: ['test@example.com'], // This will fail but tests the connection
      subject: 'Test email configuration',
      html: '<p>This is a test email.</p>'
    });

    // We expect this to fail with invalid email, but connection should work
    return error?.message?.includes('Invalid') || false;
  } catch (error) {
    console.error('Email configuration test failed:', error);
    return false;
  }
}