import nodemailer from 'nodemailer';
import type { Property, Booking, User } from '@shared/schema';

// Email configuration - using Gmail SMTP
const createEmailTransporter = () => {
  return nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'webexpertkenya@gmail.com',
      pass: 'kqrlgslklwqnmhkf' // Gmail app password (no spaces)
    }
  });
};

export interface NotificationService {
  sendPropertyInquiry(property: Property, inquirerEmail: string, message: string): Promise<boolean>;
  sendBookingConfirmation(booking: Booking, userEmail: string): Promise<boolean>;
  sendWelcomeEmail(user: User): Promise<boolean>;
  sendAdminAlert(subject: string, message: string): Promise<boolean>;
  sendPriceAlert(userEmail: string, property: Property, targetPrice: number): Promise<boolean>;
}

export class EmailNotificationService implements NotificationService {
  private transporter = createEmailTransporter();

  async sendPropertyInquiry(property: Property, inquirerEmail: string, message: string): Promise<boolean> {
    try {
      const mailOptions = {
        from: 'webexpertkenya@gmail.com',
        to: 'support@kiroservices.com', // Property owner would be here in real system
        subject: `Property Inquiry: ${property.title}`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0091B9 0%, #004F9B 100%); color: white; padding: 20px; text-align: center;">
              <h1 style="margin: 0;">🏠 KiroServices</h1>
              <p style="margin: 5px 0 0 0;">Property & Moving Solutions</p>
            </div>
            
            <div style="padding: 30px; background: #f9f9f9;">
              <h2 style="color: #004F9B;">New Property Inquiry</h2>
              
              <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h3 style="color: #0091B9; margin-top: 0;">Property Details:</h3>
                <p><strong>Title:</strong> ${property.title}</p>
                <p><strong>Type:</strong> ${property.type}</p>
                <p><strong>Price:</strong> $${property.price}</p>
                <p><strong>Location:</strong> ${property.location}</p>
              </div>
              
              <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h3 style="color: #0091B9; margin-top: 0;">Inquirer Information:</h3>
                <p><strong>Email:</strong> ${inquirerEmail}</p>
                <p><strong>Message:</strong></p>
                <p style="background: #f5f5f5; padding: 15px; border-radius: 5px;">${message}</p>
              </div>
              
              <div style="text-align: center; margin: 30px 0;">
                <a href="mailto:${inquirerEmail}" style="background: #FF6500; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block;">Reply to Inquirer</a>
              </div>
            </div>
            
            <div style="background: #004F9B; color: white; padding: 20px; text-align: center;">
              <p style="margin: 0;">© 2025 KiroServices - Mogadishu, Somalia</p>
              <p style="margin: 5px 0 0 0;">📞 +252 61 234 5678 | 📧 support@kiroservices.com</p>
            </div>
          </div>
        `
      };

      await this.transporter.sendMail(mailOptions);
      return true;
    } catch (error) {
      console.error('Error sending property inquiry email:', error);
      return false;
    }
  }

  async sendBookingConfirmation(booking: Booking, userEmail: string): Promise<boolean> {
    try {
      const mailOptions = {
        from: 'webexpertkenya@gmail.com',
        to: userEmail,
        subject: `Booking Confirmation - Moving Service`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0091B9 0%, #004F9B 100%); color: white; padding: 20px; text-align: center;">
              <h1 style="margin: 0;">🏠 KiroServices</h1>
              <p style="margin: 5px 0 0 0;">Property & Moving Solutions</p>
            </div>
            
            <div style="padding: 30px; background: #f9f9f9;">
              <h2 style="color: #004F9B;">Booking Confirmed! 🎉</h2>
              
              <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h3 style="color: #0091B9; margin-top: 0;">Service Details:</h3>
                <p><strong>Service:</strong> Moving Service</p>
                <p><strong>Date:</strong> ${new Date(booking.date).toLocaleDateString()}</p>
                <p><strong>Status:</strong> <span style="color: #00A651; font-weight: bold;">${booking.status}</span></p>
                <p><strong>Phone:</strong> ${booking.phone}</p>
              </div>
              
              <div style="background: #e8f8f5; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #0091B9;">
                <h3 style="color: #004F9B; margin-top: 0;">What's Next?</h3>
                <ul style="margin: 0; padding-left: 20px;">
                  <li>Our team will contact you within 24 hours</li>
                  <li>We'll confirm the exact time and provide preparation instructions</li>
                  <li>A confirmation SMS will be sent to your phone</li>
                </ul>
              </div>
              
              <div style="text-align: center; margin: 30px 0;">
                <a href="tel:+252612345678" style="background: #FF6500; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">📞 Call Us</a>
                <a href="https://wa.me/252612345678" style="background: #25D366; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">💬 WhatsApp</a>
              </div>
            </div>
            
            <div style="background: #004F9B; color: white; padding: 20px; text-align: center;">
              <p style="margin: 0;">© 2025 KiroServices - Mogadishu, Somalia</p>
              <p style="margin: 5px 0 0 0;">📞 +252 61 234 5678 | 📧 support@kiroservices.com</p>
            </div>
          </div>
        `
      };

      await this.transporter.sendMail(mailOptions);
      return true;
    } catch (error) {
      console.error('Error sending booking confirmation email:', error);
      return false;
    }
  }

  async sendWelcomeEmail(user: User): Promise<boolean> {
    try {
      const mailOptions = {
        from: 'webexpertkenya@gmail.com',
        to: user.email,
        subject: 'Welcome to KiroServices! 🏠',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #0091B9 0%, #004F9B 100%); color: white; padding: 20px; text-align: center;">
              <h1 style="margin: 0;">🏠 KiroServices</h1>
              <p style="margin: 5px 0 0 0;">Property & Moving Solutions</p>
            </div>
            
            <div style="padding: 30px; background: #f9f9f9;">
              <h2 style="color: #004F9B;">Welcome to KiroServices, ${user.name}! 👋</h2>
              
              <p style="font-size: 16px; line-height: 1.6;">We're excited to have you join Somalia's leading property marketplace platform. Whether you're looking to buy, rent, or need moving services, we're here to help.</p>
              
              <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h3 style="color: #0091B9; margin-top: 0;">What you can do with KiroServices:</h3>
                <ul style="line-height: 1.8;">
                  <li>🏘️ <strong>Browse Properties:</strong> Find apartments, houses, and commercial spaces in Mogadishu</li>
                  <li>🔍 <strong>Smart Search:</strong> Filter by price, location, type, and features</li>
                  <li>🚚 <strong>Moving Services:</strong> Book professional movers and transport services</li>
                  <li>📍 <strong>Interactive Map:</strong> View properties on live satellite maps</li>
                  <li>💬 <strong>Direct Contact:</strong> Connect with property owners and service providers</li>
                </ul>
              </div>
              
              <div style="text-align: center; margin: 30px 0;">
                <a href="/" style="background: #0091B9; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">🏠 Browse Properties</a>
                <a href="/moving-services" style="background: #FF6500; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">🚚 Moving Services</a>
              </div>
              
              <div style="background: #e8f8f5; padding: 20px; border-radius: 8px; margin: 20px 0;">
                <h3 style="color: #004F9B; margin-top: 0;">Need Help?</h3>
                <p style="margin: 0;">Our team is available 24/7 to assist you:</p>
                <p style="margin: 10px 0 0 0;">
                  📞 <strong>Phone:</strong> +252 61 234 5678<br>
                  💬 <strong>WhatsApp:</strong> +252 61 234 5678<br>
                  📧 <strong>Email:</strong> support@kiroservices.com
                </p>
              </div>
            </div>
            
            <div style="background: #004F9B; color: white; padding: 20px; text-align: center;">
              <p style="margin: 0;">© 2025 KiroServices - Mogadishu, Somalia</p>
              <p style="margin: 5px 0 0 0;">Your trusted partner for property and moving solutions</p>
            </div>
          </div>
        `
      };

      await this.transporter.sendMail(mailOptions);
      return true;
    } catch (error) {
      console.error('Error sending welcome email:', error);
      return false;
    }
  }

  async sendAdminAlert(subject: string, message: string): Promise<boolean> {
    try {
      const mailOptions = {
        from: 'webexpertkenya@gmail.com',
        to: 'admin@kiroservices.com',
        subject: `[ADMIN ALERT] ${subject}`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #FF6500; color: white; padding: 20px; text-align: center;">
              <h1 style="margin: 0;">⚠️ Admin Alert</h1>
              <p style="margin: 5px 0 0 0;">KiroServices Platform</p>
            </div>
            
            <div style="padding: 30px; background: #f9f9f9;">
              <h2 style="color: #004F9B;">${subject}</h2>
              <div style="background: white; padding: 20px; border-radius: 8px; border-left: 4px solid #FF6500;">
                <p style="margin: 0; font-size: 16px; line-height: 1.6;">${message}</p>
              </div>
              
              <div style="text-align: center; margin: 30px 0;">
                <a href="/admin/dashboard" style="background: #004F9B; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block;">View Admin Dashboard</a>
              </div>
            </div>
            
            <div style="background: #004F9B; color: white; padding: 20px; text-align: center;">
              <p style="margin: 0;">Sent at: ${new Date().toLocaleString()}</p>
            </div>
          </div>
        `
      };

      await this.transporter.sendMail(mailOptions);
      return true;
    } catch (error) {
      console.error('Error sending admin alert email:', error);
      return false;
    }
  }

  async sendPriceAlert(userEmail: string, property: Property, targetPrice: number): Promise<boolean> {
    try {
      const mailOptions = {
        from: 'webexpertkenya@gmail.com',
        to: userEmail,
        subject: `🎯 Price Alert: ${property.title}`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: linear-gradient(135deg, #00A651 0%, #0091B9 100%); color: white; padding: 20px; text-align: center;">
              <h1 style="margin: 0;">🎯 Price Alert</h1>
              <p style="margin: 5px 0 0 0;">KiroServices - Your price target has been reached!</p>
            </div>
            
            <div style="padding: 30px; background: #f9f9f9;">
              <h2 style="color: #004F9B;">Great news! Price drop detected 📉</h2>
              
              <div style="background: white; padding: 20px; border-radius: 8px; margin: 20px 0; border: 2px solid #00A651;">
                <h3 style="color: #0091B9; margin-top: 0;">${property.title}</h3>
                <p><strong>Current Price:</strong> <span style="color: #00A651; font-size: 20px;">$${property.price}</span></p>
                <p><strong>Your Target:</strong> $${targetPrice}</p>
                <p><strong>Location:</strong> ${property.location}</p>
                <p><strong>Type:</strong> ${property.type}</p>
              </div>
              
              <div style="text-align: center; margin: 30px 0;">
                <a href="/properties/${property.id}" style="background: #00A651; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">View Property</a>
                <a href="tel:+252612345678" style="background: #FF6500; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; display: inline-block; margin: 0 10px;">Contact Owner</a>
              </div>
            </div>
            
            <div style="background: #004F9B; color: white; padding: 20px; text-align: center;">
              <p style="margin: 0;">© 2025 KiroServices - Mogadishu, Somalia</p>
              <p style="margin: 5px 0 0 0;">📞 +252 61 234 5678 | 📧 support@kiroservices.com</p>
            </div>
          </div>
        `
      };

      await this.transporter.sendMail(mailOptions);
      return true;
    } catch (error) {
      console.error('Error sending price alert email:', error);
      return false;
    }
  }
}

// Mock SMS service for now - can be replaced with actual SMS provider
export class SMSNotificationService {
  async sendSMS(phoneNumber: string, message: string): Promise<boolean> {
    try {
      // In a real implementation, this would use Twilio, AWS SNS, or local SMS provider
      console.log(`SMS to ${phoneNumber}: ${message}`);
      
      // Simulate SMS sending delay
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      return true;
    } catch (error) {
      console.error('Error sending SMS:', error);
      return false;
    }
  }

  async sendBookingConfirmationSMS(phoneNumber: string, serviceName: string, date: string): Promise<boolean> {
    const message = `KiroServices: Your ${serviceName} booking for ${date} is confirmed! We'll contact you within 24hrs. Call: +252612345678`;
    return this.sendSMS(phoneNumber, message);
  }

  async sendPropertyAlertSMS(phoneNumber: string, propertyTitle: string): Promise<boolean> {
    const message = `KiroServices: New property "${propertyTitle}" matches your criteria! View details: kiroservices.com`;
    return this.sendSMS(phoneNumber, message);
  }
}

// Main notification service that combines email and SMS
export class NotificationManager {
  private emailService = new EmailNotificationService();
  private smsService = new SMSNotificationService();

  async sendPropertyInquiry(property: Property, inquirerEmail: string, message: string): Promise<void> {
    await this.emailService.sendPropertyInquiry(property, inquirerEmail, message);
  }

  async sendBookingConfirmation(booking: Booking, userEmail: string, userPhone?: string): Promise<void> {
    await this.emailService.sendBookingConfirmation(booking, userEmail);
    
    if (userPhone) {
      await this.smsService.sendBookingConfirmationSMS(
        userPhone, 
        'Moving Service', 
        new Date(booking.date).toLocaleDateString()
      );
    }
  }

  async sendWelcomeNotifications(user: User): Promise<void> {
    await this.emailService.sendWelcomeEmail(user);
  }

  async sendAdminAlert(subject: string, message: string): Promise<void> {
    await this.emailService.sendAdminAlert(subject, message);
  }

  async sendPriceAlert(userEmail: string, property: Property, targetPrice: number, userPhone?: string): Promise<void> {
    await this.emailService.sendPriceAlert(userEmail, property, targetPrice);
    
    if (userPhone) {
      await this.smsService.sendPropertyAlertSMS(userPhone, property.title);
    }
  }
}

export const notificationManager = new NotificationManager();