const moment = require('moment-timezone');

/**
 * WhatsApp Integration Helper
 * Generates WhatsApp share links and message templates
 */
class WhatsAppHelper {
  /**
   * Generate WhatsApp web link with pre-filled message
   * @param {string} phone - Phone number (with or without country code)
   * @param {string} message - Message to send
   * @returns {string} WhatsApp URL
   */
  static generateShareLink(phone, message) {
    // Remove all non-digit characters
    const cleanPhone = phone.replace(/\D/g, '');
    
    // Ensure phone has country code (91 for India)
    const formattedPhone = cleanPhone.startsWith('91') 
      ? cleanPhone 
      : `91${cleanPhone}`;
    
    // Encode message for URL
    const encodedMessage = encodeURIComponent(message);
    
    // Return WhatsApp web URL
    return `https://wa.me/${formattedPhone}?text=${encodedMessage}`;
  }

  /**
   * Generate payment receipt message
   */
  static generatePaymentReceipt(payment, group, member) {
    const date = this.formatDate(payment.payment_date);
    const amount = this.formatCurrency(payment.amount);
    
    return `🎉 *Payment Successful!*\n\n` +
           `👤 Name: ${member.full_name}\n` +
           `🏦 Group: ${group.name}\n` +
           `💰 Amount: ${amount}\n` +
           `📅 Date: ${date}\n` +
           `🆔 Transaction ID: ${payment.transaction_id || payment._id}\n` +
           `💳 Method: ${this.formatPaymentMethod(payment.payment_method)}\n\n` +
           `✅ Payment recorded successfully!\n` +
           `Thank you for your timely payment! 🙏\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate payment reminder message
   */
  static generatePaymentReminder(member, group, dueDate, amount, daysLeft) {
    const formattedDate = this.formatDate(dueDate);
    const formattedAmount = this.formatCurrency(amount);
    
    // Different urgency based on days left
    let urgency = '⏰';
    let urgencyText = 'Reminder';
    
    if (daysLeft <= 0) {
      urgency = '🚨';
      urgencyText = 'URGENT';
    } else if (daysLeft === 1) {
      urgency = '⚠️';
      urgencyText = 'Important';
    }
    
    return `${urgency} *Payment ${urgencyText}*\n\n` +
           `Dear ${member.full_name},\n\n` +
           `Your monthly installment payment is ${daysLeft === 0 ? 'due TODAY' : daysLeft < 0 ? 'OVERDUE' : `due in ${daysLeft} ${daysLeft === 1 ? 'day' : 'days'}`}.\n\n` +
           `📋 *Payment Details:*\n` +
           `🏦 Group: ${group.name}\n` +
           `💵 Amount Due: ${formattedAmount}\n` +
           `📅 Due Date: ${formattedDate}\n` +
           `⏳ Status: ${daysLeft < 0 ? `${Math.abs(daysLeft)} days overdue` : `${daysLeft} days remaining`}\n\n` +
           `Please make your payment at the earliest to avoid any inconvenience.\n\n` +
           `Thank you! 🙏\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate overdue payment message (more urgent)
   */
  static generateOverdueReminder(member, group, dueDate, amount, daysOverdue) {
    const formattedAmount = this.formatCurrency(amount);
    
    return `🚨 *URGENT: Payment Overdue*\n\n` +
           `Dear ${member.full_name},\n\n` +
           `Your payment for ${group.name} is now *${daysOverdue} days overdue*.\n\n` +
           `📋 *Payment Details:*\n` +
           `💵 Amount: ${formattedAmount}\n` +
           `📅 Was Due: ${this.formatDate(dueDate)}\n` +
           `⚠️ Overdue By: ${daysOverdue} days\n\n` +
           `Please settle this payment immediately to avoid penalties and maintain your membership status.\n\n` +
           `If you've already paid, please contact the group manager.\n\n` +
           `Thank you for your cooperation! 🙏\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate lottery draw result message
   */
  static generateDrawResult(group, winner, prize, month, totalMembers) {
    const formattedPrize = this.formatCurrency(prize);
    
    return `🎰 *Lucky Draw Results* 🎰\n\n` +
           `🏦 Group: *${group.name}*\n` +
           `📅 Month: ${month}\n` +
           `👥 Participants: ${totalMembers}\n\n` +
           `🎉 *WINNER ANNOUNCEMENT* 🎉\n\n` +
           `👤 Winner: *${winner.full_name}*\n` +
           `💰 Prize Amount: *${formattedPrize}*\n\n` +
           `🎊 Congratulations ${winner.full_name}! 🎊\n\n` +
           `The prize will be disbursed as per the group terms.\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate group invitation message
   */
  static generateGroupInvite(group, inviterName, appLink) {
    const totalValue = this.formatCurrency(group.total_value);
    const monthlyInstallment = this.formatCurrency(group.monthly_installment);
    
    return `👋 *You're Invited to Join a Chit Fund!*\n\n` +
           `${inviterName} has invited you to join:\n\n` +
           `🏦 *Group Name:* ${group.name}\n` +
           `💰 Total Value: ${totalValue}\n` +
           `📅 Duration: ${group.duration_months} months\n` +
           `💵 Monthly Installment: ${monthlyInstallment}\n` +
           `👥 Current Members: ${group.current_members || 0}/${group.max_members}\n` +
           `📍 Draw Date: ${group.draw_date} of every month\n\n` +
           `📱 Download LuckyChit app to join:\n` +
           `${appLink || 'Coming soon!'}\n\n` +
           `Join us for a transparent and fair chit fund experience! 🚀\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate welcome message for new member
   */
  static generateWelcomeMessage(member, group, manager) {
    return `🎉 *Welcome to ${group.name}!*\n\n` +
           `Dear ${member.full_name},\n\n` +
           `You have successfully joined the chit fund group!\n\n` +
           `📋 *Group Details:*\n` +
           `🏦 Group: ${group.name}\n` +
           `💵 Monthly Installment: ${this.formatCurrency(group.monthly_installment)}\n` +
           `📅 Payment Date: ${group.draw_date} of every month\n` +
           `⏱️ Duration: ${group.duration_months} months\n\n` +
           `👨‍💼 Manager: ${manager.full_name}\n` +
           `📞 Contact: ${manager.mobile_number}\n\n` +
           `Your first payment is due on ${group.draw_date} of this month.\n\n` +
           `Welcome aboard! 🚀\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Generate payment confirmation for manager
   */
  static generatePaymentConfirmationForManager(member, group, amount) {
    return `✅ *Payment Received*\n\n` +
           `Payment recorded for ${member.full_name}\n\n` +
           `🏦 Group: ${group.name}\n` +
           `💰 Amount: ${this.formatCurrency(amount)}\n` +
           `📅 Date: ${this.formatDate(new Date())}\n\n` +
           `_Manager Notification_`;
  }

  /**
   * Generate group status update
   */
  static generateGroupStatusUpdate(group, status, message) {
    const statusEmoji = {
      'forming': '📝',
      'active': '✅',
      'completed': '🎉',
      'cancelled': '❌'
    };

    return `${statusEmoji[status] || '📢'} *Group Status Update*\n\n` +
           `🏦 Group: ${group.name}\n` +
           `📊 Status: ${status.toUpperCase()}\n\n` +
           `${message}\n\n` +
           `_Powered by LuckyChit_`;
  }

  /**
   * Format date in readable format
   */
  static formatDate(date) {
    return moment(date).tz('Asia/Kolkata').format('DD MMM YYYY');
  }

  /**
   * Format currency in Indian format
   */
  static formatCurrency(amount) {
    return '₹' + amount.toLocaleString('en-IN');
  }

  /**
   * Format payment method
   */
  static formatPaymentMethod(method) {
    const methods = {
      'upi': 'UPI',
      'bank_transfer': 'Bank Transfer',
      'cash': 'Cash',
      'cheque': 'Cheque',
      'card': 'Card'
    };
    return methods[method] || method;
  }

  /**
   * Get days between two dates
   */
  static getDaysUntil(date) {
    const today = moment().tz('Asia/Kolkata').startOf('day');
    const targetDate = moment(date).tz('Asia/Kolkata').startOf('day');
    return targetDate.diff(today, 'days');
  }

  /**
   * Calculate due date for a group
   */
  static calculateDueDate(group, monthNumber) {
    const startDate = moment(group.start_date).tz('Asia/Kolkata');
    return startDate.add(monthNumber - 1, 'months').date(group.draw_date);
  }
}

module.exports = WhatsAppHelper;

