const nodemailer = require('nodemailer');

const createTransporter = () => {
  const smtpPort = parseInt(process.env.SMTP_PORT || '587');
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST || 'smtp.ethereal.email',
    port: smtpPort,
    secure: smtpPort === 465,
    auth: {
      user: process.env.SMTP_USER || '',
      pass: process.env.SMTP_PASS || '',
    },
  });
};

const sendEmail = async (to, subject, html) => {
  try {
    const transporter = createTransporter();
    await transporter.sendMail({
      from: '"Tok Tokkie Shuttles" <app@shanss.org>',
      to,
      subject,
      html,
    });
    console.log(`[Email] Sent "${subject}" to ${to}`);
    return true;
  } catch (error) {
    console.warn('[Email] Failed to send:', error.message);
    return false;
  }
};

const notifyBookingConfirmation = async (booking) => {
  const subject = `Booking Confirmed - ${booking.booking_reference}`;
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #16A34A;">Tok Tokkie Shuttles</h2>
      <h3>Booking Confirmed</h3>
      <p>Hi ${booking.customer_name},</p>
      <p>Your booking <strong>${booking.booking_reference}</strong> has been confirmed.</p>
      <table style="width: 100%; border-collapse: collapse;">
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Reference:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">${booking.booking_reference}</td></tr>
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Passengers:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">${booking.number_of_passengers}</td></tr>
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Total:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">N$${parseFloat(booking.total_amount).toFixed(2)}</td></tr>
      </table>
      <p style="margin-top: 20px;">Thank you for choosing Tok Tokkie Shuttles!</p>
      <p style="color: #666; font-size: 12px;">Tok Tokkie Shuttles Namibia</p>
    </div>
  `;
  return sendEmail(booking.customer_email, subject, html);
};

const notifyTripReminder = async (customerEmail, customerName, reference, departureDay, departureTime, hoursUntil) => {
  const subject = `Trip Reminder - ${reference} departs in ${hoursUntil} hour(s)`;
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #16A34A;">Tok Tokkie Shuttles</h2>
      <h3>Trip Reminder</h3>
      <p>Hi ${customerName},</p>
      <p>Your trip <strong>${reference}</strong> departs in <strong>${hoursUntil} hour(s)</strong>.</p>
      <p><strong>Departure:</strong> ${departureDay}s at ${departureTime}</p>
      <p>Please arrive at least 30 minutes before departure.</p>
      <p style="color: #666; font-size: 12px;">Tok Tokkie Shuttles Namibia</p>
    </div>
  `;
  return sendEmail(customerEmail, subject, html);
};

const notifyNewTripAvailable = async (customerEmail, customerName, route, departureDay, departureTime, price) => {
  const subject = `New Trip Available - ${route}`;
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #16A34A;">Tok Tokkie Shuttles</h2>
      <h3>New Trip Available!</h3>
      <p>Hi ${customerName},</p>
      <p>A new trip has been added:</p>
      <table style="width: 100%; border-collapse: collapse;">
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Route:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">${route}</td></tr>
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Departure:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">${departureDay}s at ${departureTime}</td></tr>
        <tr><td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>Price:</strong></td><td style="padding: 8px; border-bottom: 1px solid #ddd;">N$${parseFloat(price).toFixed(2)}</td></tr>
      </table>
      <p style="margin-top: 20px;">Book now on the app!</p>
      <p style="color: #666; font-size: 12px;">Tok Tokkie Shuttles Namibia</p>
    </div>
  `;
  return sendEmail(customerEmail, subject, html);
};

const notifyTripStatus = async (customerEmail, customerName, reference, status) => {
  const subject = `Trip ${status} - ${reference}`;
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
      <h2 style="color: #16A34A;">Tok Tokkie Shuttles</h2>
      <h3>Trip ${status}</h3>
      <p>Hi ${customerName},</p>
      <p>Your trip <strong>${reference}</strong> has <strong>${status.toLowerCase()}</strong>.</p>
      ${status === 'Started' ? '<p>Your driver is on the way. Track your trip in real-time on the app.</p>' : ''}
      ${status === 'Ended' ? '<p>We hope you had a great journey! Please leave a review on the app.</p>' : ''}
      <p style="color: #666; font-size: 12px;">Tok Tokkie Shuttles Namibia</p>
    </div>
  `;
  return sendEmail(customerEmail, subject, html);
};

module.exports = {
  sendEmail,
  notifyBookingConfirmation,
  notifyTripReminder,
  notifyNewTripAvailable,
  notifyTripStatus,
};
