import { qrGenerator } from './qr-generator';

interface EmailTemplate {
  title: string;
  subject: string;
  previewText: string;
  html: string;
  text: string;
  ctaText: string;
}

interface EventData {
  id: string;
  title: string;
  description: string;
  venue: string;
  start_time: string;
  end_time: string;
  slug: string;
  image_url?: string;
  social_links?: any;
  website_url?: string;
  contact_email?: string;
  organizations: {
    name: string;
    logo?: string;
    social_links?: any;
    website_url?: string;
    contact_email?: string;
  };
}

class EmailTemplateGenerator {
  /**
   * Generate email templates for the event
   */
  async generateTemplates(event: EventData): Promise<EmailTemplate[]> {
    const ticketUrl = `${import.meta.env.PUBLIC_SITE_URL || 'https://portal.blackcanyontickets.com'}/e/${event.slug}`;
    
    // Generate QR code for email
    const qrCode = await qrGenerator.generateEventQR(event.slug, {
      size: 200,
      color: { dark: '#000000', light: '#FFFFFF' }
    });

    const templates: EmailTemplate[] = [];

    // Primary invitation template
    templates.push(await this.generateInvitationTemplate(event, ticketUrl, qrCode.dataUrl));
    
    // Reminder template
    templates.push(await this.generateReminderTemplate(event, ticketUrl, qrCode.dataUrl));
    
    // Last chance template
    templates.push(await this.generateLastChanceTemplate(event, ticketUrl, qrCode.dataUrl));

    return templates;
  }

  /**
   * Generate primary invitation email template
   */
  private async generateInvitationTemplate(event: EventData, ticketUrl: string, qrCodeDataUrl: string): Promise<EmailTemplate> {
    const eventDate = new Date(event.start_time);
    const formattedDate = eventDate.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    const formattedTime = eventDate.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });

    const subject = `You're Invited: ${event.title}`;
    const previewText = `Join us on ${formattedDate} at ${event.venue}`;
    const ctaText = 'Get Your Tickets';

    const html = this.generateEmailHTML({
      event,
      ticketUrl,
      qrCodeDataUrl,
      formattedDate,
      formattedTime,
      subject,
      ctaText,
      template: 'invitation'
    });

    const text = this.generateEmailText({
      event,
      ticketUrl,
      formattedDate,
      formattedTime,
      template: 'invitation'
    });

    return {
      title: 'Event Invitation Email',
      subject,
      previewText,
      html,
      text,
      ctaText
    };
  }

  /**
   * Generate reminder email template
   */
  private async generateReminderTemplate(event: EventData, ticketUrl: string, qrCodeDataUrl: string): Promise<EmailTemplate> {
    const eventDate = new Date(event.start_time);
    const formattedDate = eventDate.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    const formattedTime = eventDate.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });

    const subject = `Don't Forget: ${event.title} is Coming Up!`;
    const previewText = `Event reminder for ${formattedDate}`;
    const ctaText = 'Secure Your Spot';

    const html = this.generateEmailHTML({
      event,
      ticketUrl,
      qrCodeDataUrl,
      formattedDate,
      formattedTime,
      subject,
      ctaText,
      template: 'reminder'
    });

    const text = this.generateEmailText({
      event,
      ticketUrl,
      formattedDate,
      formattedTime,
      template: 'reminder'
    });

    return {
      title: 'Event Reminder Email',
      subject,
      previewText,
      html,
      text,
      ctaText
    };
  }

  /**
   * Generate last chance email template
   */
  private async generateLastChanceTemplate(event: EventData, ticketUrl: string, qrCodeDataUrl: string): Promise<EmailTemplate> {
    const eventDate = new Date(event.start_time);
    const formattedDate = eventDate.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    const formattedTime = eventDate.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });

    const subject = `⏰ Last Chance: ${event.title} - Limited Tickets Remaining`;
    const previewText = `Final opportunity to secure your tickets`;
    const ctaText = 'Get Tickets Now';

    const html = this.generateEmailHTML({
      event,
      ticketUrl,
      qrCodeDataUrl,
      formattedDate,
      formattedTime,
      subject,
      ctaText,
      template: 'last_chance'
    });

    const text = this.generateEmailText({
      event,
      ticketUrl,
      formattedDate,
      formattedTime,
      template: 'last_chance'
    });

    return {
      title: 'Last Chance Email',
      subject,
      previewText,
      html,
      text,
      ctaText
    };
  }

  /**
   * Generate HTML email content
   */
  private generateEmailHTML(params: any): string {
    const { event, ticketUrl, qrCodeDataUrl, formattedDate, formattedTime, subject, ctaText, template } = params;
    
    const logoImg = event.organizations.logo ? 
      `<img src="${event.organizations.logo}" alt="${event.organizations.name}" style="height: 60px; width: auto;">` : 
      `<h2 style="margin: 0; color: #1877F2;">${event.organizations.name}</h2>`;

    const eventImg = event.image_url ? 
      `<img src="${event.image_url}" alt="${event.title}" style="width: 100%; max-width: 600px; height: auto; border-radius: 12px; margin: 20px 0;">` : 
      '';

    const urgencyText = template === 'last_chance' ? 
      `<div style="background: #FF6B35; color: white; padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center; font-weight: bold;">
        ⏰ Limited Tickets Available - Don't Miss Out!
      </div>` : '';

    const socialLinks = this.generateSocialLinksHTML(event.social_links || event.organizations.social_links);

    return `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${subject}</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #1877F2 0%, #4267B2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .content {
            padding: 40px 30px;
        }
        
        .event-details {
            background: #f8fafc;
            border-radius: 12px;
            padding: 25px;
            margin: 25px 0;
            border-left: 4px solid #1877F2;
        }
        
        .cta-button {
            display: inline-block;
            background: linear-gradient(135deg, #1877F2 0%, #4267B2 100%);
            color: white;
            padding: 15px 30px;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 16px;
            margin: 20px 0;
            transition: transform 0.2s;
        }
        
        .cta-button:hover {
            transform: translateY(-2px);
        }
        
        .qr-section {
            text-align: center;
            margin: 30px 0;
            padding: 20px;
            background: #f8fafc;
            border-radius: 12px;
        }
        
        .footer {
            background: #f8fafc;
            padding: 30px;
            text-align: center;
            font-size: 14px;
            color: #666;
        }
        
        .social-links {
            margin: 20px 0;
        }
        
        .social-links a {
            color: #1877F2;
            text-decoration: none;
            margin: 0 10px;
        }
        
        @media (max-width: 600px) {
            .email-container {
                margin: 10px;
                border-radius: 12px;
            }
            
            .content {
                padding: 25px 20px;
            }
            
            .header {
                padding: 25px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            ${logoImg}
            <h1 style="margin: 15px 0 0 0; font-weight: 300; font-size: 28px;">${event.title}</h1>
        </div>
        
        <div class="content">
            ${urgencyText}
            
            <p style="font-size: 18px; color: #1877F2; font-weight: 600;">
                ${template === 'invitation' ? "You're cordially invited to join us for an unforgettable experience!" : 
                  template === 'reminder' ? "Just a friendly reminder about your upcoming event!" :
                  "This is your final opportunity to secure your tickets!"}
            </p>
            
            ${eventImg}
            
            ${event.description ? `<p style="font-size: 16px; line-height: 1.7; margin: 20px 0;">${event.description}</p>` : ''}
            
            <div class="event-details">
                <h3 style="margin: 0 0 15px 0; color: #1877F2;">Event Details</h3>
                <p style="margin: 8px 0; font-size: 16px;"><strong>📅 Date:</strong> ${formattedDate}</p>
                <p style="margin: 8px 0; font-size: 16px;"><strong>⏰ Time:</strong> ${formattedTime}</p>
                <p style="margin: 8px 0; font-size: 16px;"><strong>📍 Venue:</strong> ${event.venue}</p>
            </div>
            
            <div style="text-align: center; margin: 30px 0;">
                <a href="${ticketUrl}" class="cta-button">${ctaText}</a>
            </div>
            
            <div class="qr-section">
                <h4 style="margin: 0 0 15px 0; color: #333;">Quick Access</h4>
                <img src="${qrCodeDataUrl}" alt="QR Code for ${event.title}" style="width: 150px; height: 150px;">
                <p style="margin: 10px 0 0 0; font-size: 14px; color: #666;">Scan with your phone to get tickets instantly</p>
            </div>
            
            ${template === 'last_chance' ? `
            <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 20px 0;">
                <h4 style="margin: 0 0 10px 0; color: #856404;">⚠️ Limited Time Offer</h4>
                <p style="margin: 0; color: #856404;">Tickets are selling fast! Don't wait - secure your spot today.</p>
            </div>
            ` : ''}
        </div>
        
        <div class="footer">
            <p>Questions? Contact us at ${event.contact_email || event.organizations.contact_email || 'hello@blackcanyontickets.com'}</p>
            
            ${socialLinks}
            
            <p style="margin: 20px 0 0 0; font-size: 12px; color: #999;">
                This email was sent by ${event.organizations.name}. 
                ${event.organizations.website_url ? `Visit our website: <a href="${event.organizations.website_url}" style="color: #1877F2;">${event.organizations.website_url}</a>` : ''}
            </p>
        </div>
    </div>
</body>
</html>`;
  }

  /**
   * Generate plain text email content
   */
  private generateEmailText(params: any): string {
    const { event, ticketUrl, formattedDate, formattedTime, template } = params;
    
    const urgencyText = template === 'last_chance' ? 
      '⏰ LIMITED TICKETS AVAILABLE - DON\'T MISS OUT!\n\n' : '';

    return `
${event.title}
${event.organizations.name}

${urgencyText}${template === 'invitation' ? "You're cordially invited to join us for an unforgettable experience!" : 
  template === 'reminder' ? "Just a friendly reminder about your upcoming event!" :
  "This is your final opportunity to secure your tickets!"}

EVENT DETAILS:
📅 Date: ${formattedDate}
⏰ Time: ${formattedTime}
📍 Venue: ${event.venue}

${event.description ? `${event.description}\n\n` : ''}

Get your tickets now: ${ticketUrl}

Questions? Contact us at ${event.contact_email || event.organizations.contact_email || 'hello@blackcanyontickets.com'}

--
${event.organizations.name}
${event.organizations.website_url || ''}
`.trim();
  }

  /**
   * Generate social media links HTML
   */
  private generateSocialLinksHTML(socialLinks: any): string {
    if (!socialLinks) return '';

    const links: string[] = [];
    
    if (socialLinks.facebook) {
      links.push(`<a href="${socialLinks.facebook}">Facebook</a>`);
    }
    if (socialLinks.instagram) {
      links.push(`<a href="${socialLinks.instagram}">Instagram</a>`);
    }
    if (socialLinks.twitter) {
      links.push(`<a href="${socialLinks.twitter}">Twitter</a>`);
    }
    if (socialLinks.linkedin) {
      links.push(`<a href="${socialLinks.linkedin}">LinkedIn</a>`);
    }

    if (links.length === 0) return '';

    return `
    <div class="social-links">
        <p style="margin: 0 0 10px 0;">Follow us:</p>
        ${links.join(' | ')}
    </div>`;
  }

  /**
   * Generate email subject line variations
   */
  generateSubjectVariations(event: EventData): string[] {
    return [
      `You're Invited: ${event.title}`,
      `🎉 Join us for ${event.title}`,
      `Exclusive Event: ${event.title}`,
      `Save the Date: ${event.title}`,
      `${event.title} - Tickets Available Now`,
      `Experience ${event.title} at ${event.venue}`,
      `Don't Miss: ${event.title}`
    ];
  }
}

export const emailTemplateGenerator = new EmailTemplateGenerator();