const cron = require('node-cron');
const AmbulanceRequest = require('../models/AmbulanceRequest');
const { sendEmail } = require('../config/email');

// Use the same constants as other email functions
const MAILTRAP_FROM_EMAIL = process.env.MAILTRAP_FROM_EMAIL || 'hello@sigmaconnect.org';
const MAILTRAP_FROM_NAME = process.env.MAILTRAP_FROM_NAME || 'EMS App';

/**
 * Scheduled job to send daily summary email at 3:00 AM
 * This job runs every day at 03:00 and sends a summary of yesterday's requests
 */
function scheduleDailySummaryEmail() {
  // Schedule job to run every day at 03:00 AM
  cron.schedule('0 3 * * *', async () => {
    console.log('Running daily summary email job at 03:00 AM...');
    
    try {
      // Get yesterday's date range
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      
      // Set start of yesterday (00:00:00)
      const startOfYesterday = new Date(yesterday);
      startOfYesterday.setHours(0, 0, 0, 0);
      
      // Set end of yesterday (23:59:59)
      const endOfYesterday = new Date(yesterday);
      endOfYesterday.setHours(23, 59, 59, 999);

      console.log(`Fetching requests from ${startOfYesterday.toISOString()} to ${endOfYesterday.toISOString()}`);

      // Get all requests from yesterday
      const requests = await new Promise((resolve, reject) => {
        AmbulanceRequest.findByDateRange(startOfYesterday, endOfYesterday, (err, results) => {
          if (err) {
            console.error('Error fetching yesterday\'s requests:', err);
            reject(err);
          } else {
            resolve(results);
          }
        });
      });

      console.log(`Found ${requests.length} requests from yesterday`);

      // Calculate summary statistics
      const summary = calculateRequestSummary(requests);
      
      // Send summary email
      await sendDailySummaryEmail(summary, requests, yesterday);
      
      console.log('Daily summary email sent successfully');
      
    } catch (error) {
      console.error('Error in daily summary email job:', error);
    }
  });

  console.log('Daily summary email job scheduled to run every day at 03:00 AM');
  console.log(`Current time: ${new Date().toLocaleString()}`);
}

/**
 * Calculate summary statistics for requests
 */
function calculateRequestSummary(requests) {
  const summary = {
    total: requests.length,
    pending: 0,
    dispatched: 0,
    completed: 0,
    cancelled: 0
  };

  requests.forEach(request => {
    switch (request.status?.toLowerCase()) {
      case 'pending':
        summary.pending++;
        break;
      case 'dispatched':
        summary.dispatched++;
        break;
      case 'completed':
        summary.completed++;
        break;
      case 'cancelled':
        summary.cancelled++;
        break;
    }
  });

  return {
    title: 'Daily Summary',
    message: `Yesterday's summary: ${summary.total} requests, ${summary.pending} pending, ${summary.dispatched} dispatched, ${summary.completed} completed, ${summary.cancelled} cancelled.`,
    data: summary
  };
}

/**
 * Send daily summary email to developers
 */
async function sendDailySummaryEmail(summary, requests, date) {
  const dateStr = date.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });

  const emailData = {
    from: {
      email: MAILTRAP_FROM_EMAIL,
      name: MAILTRAP_FROM_NAME
    },
    to: [
      {
        email: 'andrew@sigmagroupmw.com'
      },
      {
        email: 'chirambol@masm.mw'
      }
    ],
    subject: `EMS Daily Summary - ${dateStr}`,
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
        <h1 style="color: #333; margin-bottom: 20px; font-size: 20px;">EMS Daily Summary - ${dateStr}</h1>
      

        <!-- Detailed Breakdown -->
        <div style="margin: 30px 0;">
          <h3 style="color: #333; font-size: 18px; margin-bottom: 15px;">Detailed Breakdown</h3>
          <table style="width: 100%; border-collapse: collapse; margin-top: 10px;">
            <tr style="background: #f8f9fa;">
              <th style="padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6; color: #495057;">Status</th>
              <th style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6; color: #495057;">Count</th>
              <th style="padding: 12px; text-align: right; border-bottom: 2px solid #dee2e6; color: #495057;">Percentage</th>
            </tr>
            <tr>
              <td style="padding: 12px; border-bottom: 1px solid #dee2e6;">🟡 Pending</td>
              <td style="padding: 12px; text-align: center; border-bottom: 1px solid #dee2e6;">${summary.data.pending}</td>
              <td style="padding: 12px; text-align: right; border-bottom: 1px solid #dee2e6;">${summary.data.total > 0 ? ((summary.data.pending / summary.data.total) * 100).toFixed(1) : 0}%</td>
            </tr>
            <tr>
              <td style="padding: 12px; border-bottom: 1px solid #dee2e6;">🔵 Dispatched</td>
              <td style="padding: 12px; text-align: center; border-bottom: 1px solid #dee2e6;">${summary.data.dispatched}</td>
              <td style="padding: 12px; text-align: right; border-bottom: 1px solid #dee2e6;">${summary.data.total > 0 ? ((summary.data.dispatched / summary.data.total) * 100).toFixed(1) : 0}%</td>
            </tr>
            <tr>
              <td style="padding: 12px; border-bottom: 1px solid #dee2e6;">🟢 Completed</td>
              <td style="padding: 12px; text-align: center; border-bottom: 1px solid #dee2e6;">${summary.data.completed}</td>
              <td style="padding: 12px; text-align: right; border-bottom: 1px solid #dee2e6;">${summary.data.total > 0 ? ((summary.data.completed / summary.data.total) * 100).toFixed(1) : 0}%</td>
            </tr>
            ${summary.data.cancelled > 0 ? `
            <tr>
              <td style="padding: 12px; border-bottom: 1px solid #dee2e6;">🔴 Cancelled</td>
              <td style="padding: 12px; text-align: center; border-bottom: 1px solid #dee2e6;">${summary.data.cancelled}</td>
              <td style="padding: 12px; text-align: right; border-bottom: 1px solid #dee2e6;">${((summary.data.cancelled / summary.data.total) * 100).toFixed(1)}%</td>
            </tr>
            ` : ''}
            <tr style="background: #f1f3f4; font-weight: bold;">
              <td style="padding: 12px; border-bottom: 2px solid #dee2e6;">📊 Total</td>
              <td style="padding: 12px; text-align: center; border-bottom: 2px solid #dee2e6;">${summary.data.total}</td>
              <td style="padding: 12px; text-align: right; border-bottom: 2px solid #dee2e6;">100.0%</td>
            </tr>
          </table>
        </div>

        <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0;">
          <p style="color: #666; font-size: 14px;">This is an automated daily summary from EMS system.</p>
          <p style="color: #999; font-size: 12px; margin-top: 10px;">&copy; 2026 EMS. All rights reserved.</p>
        </div>
      </div>
    `,
    category: 'Daily Summary'
  };

  // Send email using existing email configuration
  return sendEmail(emailData);
}

module.exports = {
  scheduleDailySummaryEmail,
  calculateRequestSummary,
  sendDailySummaryEmail
};
