import { MailService } from '@sendgrid/mail';
import type { IStorage } from './storage.js';

export interface EmailDigestData {
  userId: number;
  userName: string;
  userEmail: string;
  hasNewMessages: boolean;
  hasNewNotifications: boolean;
  messageCount: number;
  notificationCount: number;
  messages: Array<{
    id: number;
    sender: string;
    itemName: string;
    excerpt: string;
    createdAt: Date;
  }>;
  notifications: Array<{
    id: number;
    type: string;
    title: string;
    message: string;
    createdAt: Date;
  }>;
}

export class EmailNotificationService {
  private mailService: MailService;
  private storage: IStorage;

  constructor(storage: IStorage) {
    const apiKey = process.env.SENDGRID_API_KEY;
    if (!apiKey) {
      throw new Error("SENDGRID_API_KEY environment variable must be set");
    }

    if (!apiKey.startsWith('SG.')) {
      console.log(`⚠️  API key format check failed. Key starts with: "${apiKey.substring(0, 10)}..."`);
    } else {
      console.log('✓ SendGrid API key validated successfully');
    }

    this.mailService = new MailService();
    this.mailService.setApiKey(apiKey);
    this.storage = storage;
  }

  /**
   * Send daily digest email to user or temporary email address
   */
  async sendDailyDigest(digestData: EmailDigestData, temporaryMode = true, temporaryEmail = "manager@tatacommons.com"): Promise<boolean> {
    try {
      const recipientEmail = temporaryMode ? temporaryEmail : digestData.userEmail;
      const subject = `To ${digestData.userName}: LL Messages and Notifications`;
      
      const htmlContent = this.generateDigestHTML(digestData);
      const textContent = this.generateDigestText(digestData);

      const emailData = {
        to: recipientEmail,
        from: {
          email: 'notifications@locallendables.com',
          name: 'LocalLendables'
        },
        subject: subject,
        text: textContent,
        html: htmlContent,
        trackingSettings: {
          clickTracking: {
            enable: true
          }
        }
      };

      const response = await this.mailService.send(emailData);
      
      // Log successful send
      await this.storage.createEmailLog({
        userId: digestData.userId,
        recipientEmail,
        subject,
        messageCount: digestData.messageCount,
        notificationCount: digestData.notificationCount,
        status: 'sent',
        sendgridMessageId: response[0].headers['x-message-id'] || null
      });

      console.log(`Daily digest email sent to ${recipientEmail} for user ${digestData.userName} (ID: ${digestData.userId})`);
      return true;

    } catch (error) {
      console.error('SendGrid email error:', error);
      
      // Log failed send
      await this.storage.createEmailLog({
        userId: digestData.userId,
        recipientEmail: temporaryMode ? temporaryEmail : digestData.userEmail,
        subject: `To ${digestData.userName}: LL Messages and Notifications`,
        messageCount: digestData.messageCount,
        notificationCount: digestData.notificationCount,
        status: 'failed',
        errorMessage: error instanceof Error ? error.message : 'Unknown error'
      });

      return false;
    }
  }

  /**
   * Generate HTML content for daily digest email
   */
  private generateDigestHTML(data: EmailDigestData): string {
    const messagesSection = data.messages.length > 0 ? `
      <div style="margin-bottom: 30px;">
        <h2 style="color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px;">
          New Messages (${data.messageCount})
        </h2>
        ${data.messages.map(msg => `
          <div style="background: #f8fafc; border-left: 4px solid #3b82f6; padding: 15px; margin-bottom: 15px; border-radius: 4px;">
            <div style="font-weight: bold; color: #1e40af; margin-bottom: 5px;">
              From: ${msg.sender} • Item: ${msg.itemName}
            </div>
            <div style="color: #475569; margin-bottom: 8px;">${msg.excerpt}</div>
            <div style="font-size: 12px; color: #64748b;">
              ${msg.createdAt.toLocaleDateString('en-US', { 
                weekday: 'short', 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: 'numeric',
                minute: '2-digit'
              })}
            </div>
          </div>
        `).join('')}
      </div>
    ` : '';

    const notificationsSection = data.notifications.length > 0 ? `
      <div style="margin-bottom: 30px;">
        <h2 style="color: #dc2626; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px;">
          New Notifications (${data.notificationCount})
        </h2>
        ${data.notifications.map(notif => `
          <div style="background: #fef2f2; border-left: 4px solid #ef4444; padding: 15px; margin-bottom: 15px; border-radius: 4px;">
            <div style="font-weight: bold; color: #dc2626; margin-bottom: 5px;">
              ${notif.title}
            </div>
            <div style="color: #475569; margin-bottom: 8px;">${notif.message}</div>
            <div style="font-size: 12px; color: #64748b;">
              ${notif.createdAt.toLocaleDateString('en-US', { 
                weekday: 'short', 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: 'numeric',
                minute: '2-digit'
              })}
            </div>
          </div>
        `).join('')}
      </div>
    ` : '';

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>LocalLendables Daily Digest</title>
      </head>
      <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
        <div style="background: #1e40af; color: white; padding: 20px; border-radius: 8px 8px 0 0; text-align: center;">
          <h1 style="margin: 0; font-size: 24px;">LocalLendables</h1>
          <p style="margin: 5px 0 0 0; opacity: 0.9;">Daily Message & Notification Digest</p>
        </div>
        
        <div style="background: #ffffff; border: 1px solid #e5e7eb; border-top: none; padding: 30px; border-radius: 0 0 8px 8px;">
          <h2 style="color: #1e40af; margin-top: 0;">Hello ${data.userName}!</h2>
          
          <p style="color: #64748b; margin-bottom: 30px;">
            Here's your daily summary of new activity on LocalLendables:
          </p>

          ${messagesSection}
          ${notificationsSection}

          ${data.messageCount === 0 && data.notificationCount === 0 ? `
            <div style="text-align: center; padding: 40px 20px; background: #f1f5f9; border-radius: 8px; color: #64748b;">
              <h3 style="color: #475569; margin-bottom: 10px;">All caught up!</h3>
              <p style="margin: 0;">No new messages or notifications since yesterday.</p>
            </div>
          ` : ''}

          <div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
            <a href="https://locallendables.com/dashboard" 
               style="background: #2563eb; color: white; text-decoration: none; padding: 12px 24px; border-radius: 6px; display: inline-block; font-weight: bold;">
              Visit LocalLendables Dashboard
            </a>
          </div>
        </div>
        
        <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #9ca3af;">
          <p>This email was sent by LocalLendables • Community Resource Sharing Platform</p>
          <p>Temporary development mode: All emails routed to manager@tatacommons.com</p>
        </div>
      </body>
      </html>
    `;
  }

  /**
   * Generate plain text content for daily digest email
   */
  private generateDigestText(data: EmailDigestData): string {
    let content = `LocalLendables Daily Digest for ${data.userName}\n\n`;
    
    if (data.messageCount > 0) {
      content += `NEW MESSAGES (${data.messageCount}):\n`;
      content += "=" + "=".repeat(30) + "\n\n";
      
      data.messages.forEach(msg => {
        content += `From: ${msg.sender}\n`;
        content += `Item: ${msg.itemName}\n`;
        content += `Message: ${msg.excerpt}\n`;
        content += `Date: ${msg.createdAt.toLocaleDateString('en-US', { 
          weekday: 'short', 
          year: 'numeric', 
          month: 'short', 
          day: 'numeric',
          hour: 'numeric',
          minute: '2-digit'
        })}\n\n`;
      });
    }

    if (data.notificationCount > 0) {
      content += `NEW NOTIFICATIONS (${data.notificationCount}):\n`;
      content += "=" + "=".repeat(35) + "\n\n";
      
      data.notifications.forEach(notif => {
        content += `${notif.title}\n`;
        content += `${notif.message}\n`;
        content += `Date: ${notif.createdAt.toLocaleDateString('en-US', { 
          weekday: 'short', 
          year: 'numeric', 
          month: 'short', 
          day: 'numeric',
          hour: 'numeric',
          minute: '2-digit'
        })}\n\n`;
      });
    }

    if (data.messageCount === 0 && data.notificationCount === 0) {
      content += "All caught up! No new messages or notifications since yesterday.\n\n";
    }

    content += "Visit your LocalLendables dashboard: https://locallendables.com/dashboard\n\n";
    content += "---\n";
    content += "This email was sent by LocalLendables\n";
    content += "Temporary development mode: All emails routed to manager@tatacommons.com\n";

    return content;
  }

  /**
   * Test email connectivity
   */
  async testConnection(): Promise<boolean> {
    try {
      const testEmail = {
        to: 'manager@tatacommons.com',
        from: {
          email: 'notifications@locallendables.com',
          name: 'LocalLendables'
        },
        subject: 'LocalLendables Email System Test',
        text: 'This is a test email to verify SendGrid connectivity.',
        html: '<p>This is a test email to verify SendGrid connectivity.</p>'
      };

      await this.mailService.send(testEmail);
      console.log('Email system test successful');
      return true;
    } catch (error) {
      console.error('Email system test failed:', error);
      return false;
    }
  }
}